, int >) 在 C++ 中?,c++,dictionary,set"/>

首页 > 解决方案 > 如何迭代集合的映射(std::map, int >) 在 C++ 中?

问题描述

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

      key      value

例如:[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";
}

但它显示错误。帮助!

标签: c++dictionaryset

解决方案


您只能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';
}

或可读的替代方案:

for (const auto& [key,value] : mp)
{
    for (const auto& el : key)
    {
        std::cout << el << ", ";
    }
    std::cout << value << '\n';
}

推荐阅读