遍历映射并将该对用作参考参数 C++11

Iterate over map and use the pair as reference parameter 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 的方式来解决这个问题。

std::mapvalue_type 及其迭代器是 std::pair<const std::string, std::string> 而不是 std::pair<std::string, std::string>。换句话说,键在 C++ 映射中始终是常量。

std::map<std::string, std::string>::value_typestd::pair<const std::string, std::string>:注意 const。如果您被允许修改一对中的键,这可能会违反映射条目按键排序的不变量。由于您使用了不同的 pair 类型,引用无法绑定到实际对象。

为了保持一致性(尤其是如果您要在某个时候对其进行模板化),我会这样定义您的函数:

void my_function(std::map<std::string, std::string>::value_type& my_arg){
    //do stuff, modify elements from the pair
}