【问题标题】:in class map what is necessity of const_iterator when we have iterator?在类映射中,当我们有迭代器时,const_iterator 的必要性是什么?
【发布时间】:2015-03-28 07:45:16
【问题描述】:

我读到该类映射同时具有const_iterator 和迭代器Typedefs,如果有const_iterator 的必要性,我很感兴趣。有什么const_iterator 可以做而迭代器不能做的吗?

link

【问题讨论】:

  • 如果您问的是set 而不是map,这个问题会更有趣很多

标签: c++ class dictionary


【解决方案1】:

您不能通过const_iterator 修改地图元素,而可以通过iterator。这是两者的主要区别。

可以从std::mapconst 实例或通过const 引用或指针获得const_iteratoriterator 不能。这是因为返回迭代器的std::map 的成员函数具有返回const_iteratorconst 重载。这是一种保持 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 实例中使用。
【解决方案2】:

const_iteratoriterator 的一个更受限制的版本,它不允许修改映射中的值。例如,begin() 被重载以返回 const_iterator 以获取 const 映射,根据定义不能存在修改 iterator 的映射。

【讨论】:

    猜你喜欢
    • 2011-07-17
    • 2010-11-16
    • 2012-08-09
    • 1970-01-01
    • 2020-11-07
    • 2016-08-01
    • 2020-12-21
    • 2021-07-06
    • 2020-02-27
    相关资源
    最近更新 更多