Как вывести на экран все значения элементов лежащих по одному ключу в std::map? вот у меня есть контейнер std::map, в нем содержится:
merlok 89-09-23
merlok 66-66-66
merlok 12-34-56
задача вывести все номера по ключу surname, где surname это merlok
#include <iostream>
#include <map>
#include <string>
struct data {
std::string number;
std::string surname;
} user;
void add(std::map<std::string, std::string>& surname_book,
std::map<std::string, std::string>& phone_book) {
while (1) {
std::cout << "Type 'show' to show the map!\n";
std::cout << "Enter a phone number: (Type '0' to exit!) ";
std::cin >> user.number;
if (user.number == "0") {
system("cls");
break;
}
std::cout << "Enter a surname: ";
std::cin >> user.surname;
phone_book.insert(
std::pair<std::string, std::string>(user.number, user.surname));
surname_book.insert(
std::pair<std::string, std::string>(user.number, user.surname));
}
}
void search_by_surname(std::map<std::string, std::string>& surname_book) {
std::string surname;
std::cout << "Enter the surname to find: ";
std::cin >> surname;
std::map<std::string, std::string>::iterator it = surname_book.begin();
if (it == surname_book.end()) {
std::cout << "Not found!\n";
} else {
std::cout << "Founds:\n";
for (it; it != surname_book.end(); it++) { //вывод всех значений по 1 ключу
std::cout << it->first << std::endl;
}
}
}
void search_by_number(std::map<std::string, std::string>& phone_book) {
std::string number;
std::cout << "Enter the number to find: ";
std::cin >> number;
std::map<std::string, std::string>::iterator it = phone_book.find(number);
std::cout << "Founds:\n";
if (it == phone_book.end()) {
std::cout << "Not found!\n";
} else {
std::cout << it->first << " " << it->second << std::endl;
}
}
int main() {
std::map<std::string, std::string> surnameBook;
std::map<std::string, std::string> phoneBook;
while (1) {
std::cout << "Type '0' to exit!\n";
std::cout << "Type 'add' | 'find':\n";
std::string choice;
std::cin >> choice;
if (choice == "0") {
system("cls");
break;
}
if (choice == "add") {
add(surnameBook, phoneBook);
} else if (choice == "find") {
std::cout << "1# Find by number\n";
std::cout << "2# Find by surname:\n";
std::cout << "Enter a number! ('1' | '2')\n";
int ans = 0;
std::cin >> ans;
switch (ans) {
case 1:
search_by_number(phoneBook);
break;
case 2:
search_by_surname(surnameBook);
break;
}
system("pause");
system("cls");
}
}
std::cout << "Program finished!\n";
}