为什么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’
答案 0 :(得分:15)
它没有返回const_iterator
,而std::set<int>
的key_type是const int
。
请记住,std::set
中的密钥是不变的。插入到集合中后,您无法更改密钥。因此,当您取消引用迭代器时,它必然会返回常量引用。所以你需要说:
const int &res = *myset.begin();