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

I-m*_*man 5 c++ const g++ set

为什么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’
Run Code Online (Sandbox Code Playgroud)

Cha*_*via 15

它不返回const_iterator,而的key_type的std::set<int>const int.

请记住,a std::set中的键是常量.插入到集合中后,您无法更改密钥.因此,当您取消引用迭代器时,它必然会返回一个常量引用.所以你需要说:

const int &res = *myset.begin();
Run Code Online (Sandbox Code Playgroud)