c++ - 如何迭代集合的映射(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";
}
但它显示错误。帮助!
解决方案
您只能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';
}
推荐阅读
- javascript - 在表情符号按钮选择器上监听事件
- javascript - 无法检测到正确的数据值
- java - 如何在新的 ActivityResult API (1.3.0-alpha05) 中获取权限请求?
- css - 锚点上的过渡无法正常工作
- mysql - MySQL GROUP_CONCAT 查询排除记录
- sql - 如何在 t-sql 中使用 patIndex 删除右括号
- sql - VB.NET SQL 语句不从 Access 数据库返回任何行
- c# - 当方法具有名称 ...Async 时,会发生异常“System.InvalidOperationException:没有路由与提供的值匹配”
- ios - 如何将数据从一个视图控制器类获取到另一个视图控制器类中以在 TableView 中显示
- json - 从 Ionic 3 迁移到 Ionic 5 - 用户数据上的 Json 函数