【发布时间】:2019-12-02 20:43:44
【问题描述】:
我只是想知道是否可以使用 const_iterator 更改/更新地图的值。
下面是sn-p的代码:
int main()
{
map <int, int> m;
m.insert(make_pair(1, 10));
map <int, int>::const_iterator itr = m.begin(); //The iterator is const_iterator
itr->second = 30;
cout << itr->second; //The value to be printed is 30, and not 10.
return 0;
}
提前感谢您分享您的想法。
【问题讨论】:
-
您能详细说明为什么您认为这应该是可能的吗?
const_iterator这个名字中的“const”怎么理解? -
代码无法编译并显示消息“错误:只读对象中成员 'std::pair
::second' 的赋值”。很明显,你不能用这段代码来做。您是否要求一种方法来规避这种行为,例如使用 const_cast或类似的东西?
标签: c++ stl stdmap const-iterator