简体   繁体   English

如何通过数组初始化 std::map?

[英]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我有一个任务来填充空std::map<char, std::set<std::string>> myMap ,由一个数组

const char* s[] = { "car", "sun", "surprise", "asteriks", "alpha", "apple" };

and print it using range based for and bindings .并使用range based forbindings打印它。 Result, should be like S: sun, surprise结果,应该像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?但是我怎样才能通过const char* s[]以正确的方式初始化这张地图?

PS I know, how to initialize it like std::map<char, std::set<std::string>> myMap = { {'a', {"abba", "abart", "audi"} } }; PS我知道,如何初始化它像 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.我在 StackOverflow 上阅读了这篇这篇文章,但我仍然不知道如何通过这个数组来做到这一点。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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