首页 > 解决方案 > 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?

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.

标签: c++stlstdmap

解决方案


这个怎么样?

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

推荐阅读