【问题标题】:How to initialize std::map by an array?如何通过数组初始化 std::map?
【发布时间】:2021-02-22 15:05:41
【问题描述】:

我的任务是用数组填充空的std::map<char, std::set<std::string>> myMap

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

并使用range based forbindings 打印它。结果,应该是S: sun, surprise

最后一个(打印的)我已经用这种方式实现了

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;
    }
}

但是我怎样才能以正确的方式通过const char* s[] 初始化这张地图呢?

附:我知道,如何像 std::mapstd::set<std::string>> myMap = { {'a', {"abba", "abart", "audi"} } }; 一样初始化它,我在 StackOverflow 上阅读了 thisthis 帖子,但我仍然不知道如何通过这个数组来做到这一点。

【问题讨论】:

  • 一个映射包含键和映射值,数组应该如何填充到映射中并不明显
  • OT:为什么不使用 range-for 循环来打印集合?

标签: c++ stl stdmap


【解决方案1】:

这个怎么样?

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

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2017-05-02
    • 2018-01-13
    相关资源
    最近更新 更多