c++ - 遍历 map 并将该对用作参考参数 C++11
问题描述
我有一个std::map
. 我想迭代它并将结果用作函数的参数。编译似乎抱怨我的对象是左值,但我无法弄清楚为什么它被视为左值。
void my_function(std::pair<std::string, std::string>& my_arg){
//do stuff, modify elements from the pair
}
std::map<std::string, std::string> my_map;
// fill the map with values...
for(auto& element : my_map){
my_function(element);
}
我可能可以使用迭代器来解决这个问题,但我想学习如何用 c++11 的方式来解决这个问题。
解决方案
value_type
ofstd::map
及其迭代器 is和std::pair<const std::string, std::string>
not std::pair<std::string, std::string>
。换句话说,键在 C++ 映射中总是不变的。
推荐阅读
- ruby-on-rails - 我不能用 Ruby 发出 ajax 请求
- python - 如何根据条件在Python中合并数据框中的两个连续记录
- python - Django 3 模板日期标签不返回任何内容
- javascript - 无法读取未定义的属性“findOne” - Vue.js、Apollo Server、GraphQL 错误
- sql - 如何从自定义格式的日期列中选择基于特定月份的 SQL Server 记录
- javascript - 如果您不指定依赖关系,那么 useEffect() 有什么意义
- clojure - 棱柱形/模式需要关键依赖?
- android - 由于 mapping.txt,uploadCrashlyticsMappingFile 任务失败?
- javascript - 显示 Div,设置超时,隐藏 Div
- python - 通过另一个列表对子列表的元素进行排序