首页 > 解决方案 > 遍历 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 的方式来解决这个问题。

标签: c++c++11stdmapauto

解决方案


value_typeofstd::map及其迭代器 is和std::pair<const std::string, std::string>not std::pair<std::string, std::string>。换句话说,键在 C++ 映射中总是不变的。


推荐阅读