如何在C ++中遍历set的映射(std :: map <std :: set <char =“”>,int>)?

时间:2019-03-03 11:36:48

标签: c++ dictionary set

对于特定集合作为键,我想增加集合出现的次数:

      key      value

ex:[a,b,c] = 3次

 [a , i ] = 2 times

以此类推。

我该如何迭代呢? 到目前为止,我写的是这个..

map<set<char> , int > mp;

for(auto const& elem : mp) {
    for(set<char> :: iterator it = elem->first.begin(); it !=elem->first.end();++it)
        cout << *it << ", ";
    cout<<mp[elem]<<" ";
cout<<"\n";
}

但显示错误。帮助!

2 个答案:

答案 0 :(得分:1)

您仅具有[{"Column 1":"A1","Column 2":"A2","Column 3":""},{"Column 1":"B1","Column 2":"B2","Column 3":"B3"},{"Column 1":"C1","Column 2":"","Column 3":"C3"}] 的访问权限,但您正在尝试使用非const设置的迭代器。那行不通。

您的代码的固定版本为:

const

或者:

for(auto const& elem : mp) {
    for(set<char>::const_iterator it = elem.first.begin(); it !=elem.first.end();++it)
        cout << *it << ", ";
    cout<<mp[elem]<<" ";
    cout<<"\n";
}

或可读的替代方法:

for (const auto& elem : mp) {
    for (auto it = elem.first.begin(); it != elem.first.end(); ++it)
        std::cout << *it << ", ";

    std::cout << elem.second << '\n';
}

答案 1 :(得分:0)

我认为您需要这样的东西:

for (const auto &map_elem : mp)
{
    for (const auto &set_elem : map_elem.first)
    {
        ...
    }
}

Live demo