【发布时间】:2015-03-28 07:45:16
【问题描述】:
我读到该类映射同时具有const_iterator 和迭代器Typedefs,如果有const_iterator 的必要性,我很感兴趣。有什么const_iterator 可以做而迭代器不能做的吗?
【问题讨论】:
-
如果您问的是
set而不是map,这个问题会更有趣很多。
标签: c++ class dictionary
我读到该类映射同时具有const_iterator 和迭代器Typedefs,如果有const_iterator 的必要性,我很感兴趣。有什么const_iterator 可以做而迭代器不能做的吗?
【问题讨论】:
set 而不是map,这个问题会更有趣很多。
标签: c++ class dictionary
您不能通过const_iterator 修改地图元素,而可以通过iterator。这是两者的主要区别。
可以从std::map 的const 实例或通过const 引用或指针获得const_iterator。 iterator 不能。这是因为返回迭代器的std::map 的成员函数具有返回const_iterator 的const 重载。这是一种保持 const 正确性的机制,不允许修改从 const 实例中获得的元素。
std::map<int, int> m;
m[0] = 42;
std::map<int, int>::iterator it = m.begin();
*it = 43; // OK
const std::map<int, int> cm;
cm[0] = 42;
std::map<int, int>::iterator it = cm.begin(); // ERROR
std::map<int, int>::const_iterator it = cm.begin(); // OK
*it = 43; // ERROR
【讨论】:
const_iterator 是iterator 的一个更受限制的版本,它不允许修改映射中的值。例如,begin() 被重载以返回 const_iterator 以获取 const 映射,根据定义不能存在修改 iterator 的映射。
【讨论】: