/* * Example: Read command-line arguments and write them into a map * with string keys and "set of int" values * * To test, for example, execute "./map-and-set-example 3 1 4 1 5 9 2 6 5 3 5 9" */ #include #include #include #include int main(int argc, char** argv) { std::map> command_line_args; for(int i = 0; i < argc; i++) { if(command_line_args.count(argv[i]) == 0) /* new key, not in the map so far */ { command_line_args[argv[i]] = std::set(); // create new set from default constructor } command_line_args[argv[i]].insert(i); } /* * note that maps (and sets) are sorted data structures, * therefore traversal will automatically be sorted by key * * let us only show the words that occurred multiple times */ for(auto i = command_line_args.begin(); i != command_line_args.end(); i++) { if(i->second.size() == 1) continue; // don't show words that occur only once /* output text value of command line argument */ std::cout << "Key: " << i->first << "\t\tValue (list of occurrences):"; /* now iterate over all the positions where it was found */ for(auto j = i->second.begin(); j != i->second.end(); j++) std::cout << "\t" << *j; std::cout << "\n"; } }