1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
#include <iostream>
#include <string>
#include <map> // or: <unordered_map>
#include <stdexcept>
enum e_countries { GGG=0, AAA, WWW, FFF, III };
struct Country {
std::string name ;
std::string flag ;
std::string head ;
e_countries e;
friend std::ostream& operator<< ( std::ostream& stm, const Country& c ) {
return stm << "Country{ name:" << c.name << " flag:" << c.flag
<< " head:" << c.head << " e:" << c.e << " }" ;
}
};
// key: name, mapped data: Country
// there may be more than one entry with the same key (many countries with the same name)
// TO DO? make the key (name) comparison case-insensitive?
using country_map = std::multimap< std::string, Country > ; // or: unordered_map
void look_up_and_print( const country_map& multimap, const std::string& name ) {
std::cout << "\n name '" << name << "' : " ;
// https://en.cppreference.com/w/cpp/container/multimap/equal_range
const auto range = multimap.equal_range(name) ;
if( range.first == range.second )
std::cout << "*** there are no countries with this name ***\n" ;
else
{
std::cout << '\n' ;
int n = 0 ;
for( auto iter = range.first ; iter != range.second ; ++iter )
std::cout << '\t' << ++n << ". " << iter->second << '\n' ;
}
}
int main() {
const country_map countries = {
{ "GGGG", { "GGGG", "hjkkd", "hhkad", GGG } },
{ "AAAA", { "AAAA", "OOO", "Ojkjs", AAA } },
{ "WWWW", { "WWWW", "Ocghaa", "Wahja", WWW } },
{ "GGGG", { "GGGG", "hjkkd2", "hhkad2", GGG } }, // duplicate key GGGG
{ "AAAA", { "AAAA", "OOO2", "Ojkjs2", AAA } }, // duplicate key AAAA
{ "FFFF", { "FFFF", "Dddaa", "Hahada", FFF } },
{ "GGGG", { "GGGG", "hjkkd3", "hhkad3", GGG } }, // duplicate key GGGG
{ "IIII", { "IIII", "Masadaa", "Iahjda", III } },
};
std::string name ;
while( std::cout << "name? " && std::cin >> name ) look_up_and_print( countries, name ) ;
}
|