Sne*_*med 3 c++ stdmap auto 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);
}
Run Code Online (Sandbox Code Playgroud)
我可能会使用迭代器来解决这个问题,但我想学习如何用c ++ 11方法来解决这个问题.
小智 8
在value_type中std::map和它的迭代器std::pair<const std::string, std::string>,而不是std::pair<std::string, std::string>.换句话说,键在C++映射中始终是常量.
std::map<std::string, std::string>::value_type是std::pair<const std::string, std::string>:注意const。如果允许您修改键对中的键,则可能会违反映射条目按键排序的不变量。由于您使用了不同的pair类型,因此引用无法绑定到实际对象。
| 归档时间: |
|
| 查看次数: |
370 次 |
| 最近记录: |