简体   繁体   中英

How to initialize std::map by an array?

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?

PS 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.

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"}
// }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM