奇怪的错误,set<int>::begin() 总是返回 const 迭代器

6
为什么 set.begin() 总是返回 const 迭代器而不是标准迭代器?
35 int test(){
36     std::set<int> myset;
37     myset.insert(2);
38     myset.insert(3);
39     int &res = *myset.begin();
40     return res;
41 }


test.cpp:39: error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int

我曾经遇到过同样的问题,有趣的是,这段代码在Visual Studio 2008中可以运行。当GCC开始抱怨时,我才发现了这一点... - smf68
1个回答

16

它并不返回一个 const_iterator,而是 std::set<int>key_typeconst int

请记住,在 std::set 中,键是常量。一旦将键插入到集合中,就不能更改它。因此,当您解引用迭代器时,它必然返回一个 常量 引用。所以您需要这样写:

const int &res = *myset.begin();

好的,我猜因为集合是按模板类型排序的,所以它需要是const,这样你就不会改变值并且是“未排序”的。 - I-man

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接