Reputation: 85
I have a task to fill empty std::map<char, std::set<std::string>> myMap
, by an array
const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };
and print it using range based for
and bindings
. Result, should be like S: sun, surprise
The last one(printing) I have already implement in this way
for (const auto& [k, v] : myMap)
{
cout << "k = " << k << endl;
std::set<std::string>::iterator it;
for (it = v.begin(); it != v.end(); ++it)
{
cout << "var = " << *it << endl;
}
}
But how can I initilase this map, by const char* s[]
in right way?
P.S. I know, how to initialize it like std::map<char, std::set<std::string>> myMap = { {'a', {"abba", "abart", "audi"} } };
and I read this and this posts on StackOverflow, but I am still have no idea, how to do this by this array.
Upvotes: 0
Views: 361
Reputation: 7324
How about this?
const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };
std::map<char, std::set<std::string>> myMap;
for (auto str : s)
myMap[str[0]].insert(str);
// Result: {
// 'a' -> {"alpha", "apple", "asteriks"},
// 'c' -> {"car"},
// 's' -> {"sun", "surprise"}
// }
Upvotes: 2