为什么std :: set似乎强制使用const_iterator? [英] Why does std::set seem to force the use of a const_iterator?

查看:79
本文介绍了为什么std :: set似乎强制使用const_iterator?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的简单程序,该程序尝试使用对其中元素的NON-const引用来迭代集合的值:

Consider the simple program below, which attempts to iterate through the values of a set using NON-const references to the elements in it:

#include <set>
#include <iostream>

class Int
{
public:
   Int(int value) : value_(value) {}
   int value() const { return value_; }
   bool operator<(const Int& other) const { return value_ < other.value(); }
private:
   int value_;
};

int
main(int argc, char** argv) {
   std::set<Int> ints;
   ints.insert(10);
   for (Int& i : ints) {
      std::cout << i.value() << std::endl;
   }
   return 0;
}

编译时,我从gcc收到错误:

When compiling this, I get an error from gcc:

test.c: In function ‘int main(int, char**)’:
test.c:18:18: error: invalid initialization of reference of type ‘Int&’ from expression of type ‘const Int’  
for (Int& i : ints) {  
              ^  

是的,我知道我实际上并不是在尝试修改for循环中的元素.但是关键是我应该能够在循环内使用非常量引用,因为集合本身不是常量限定的.如果创建一个setter函数并在循环中使用它,则会出现相同的错误.

Yes, I know I'm not actually trying to modify the elements in the for loop. But the point is that I should be able to get a non-const reference to use inside the loop, since the set itself is not const qualified. I get the same error if I create a setter function and use that in the loop.

推荐答案

集合就像地图一样,没有值,只有键.由于这些键用于加速集合上操作的树,因此它们无法更改.因此,所有元素必须为常量,以防止破坏基础树的约束.

A set is like a map with no values, only keys. Since those keys are used for a tree that accelerates operations on the set, they cannot change. Thus all elements must be const to keep the constraints of the underlying tree from being broken.

这篇关于为什么std :: set似乎强制使用const_iterator?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆