Strange error, set<int>::begin() always returning const iterator

笑着哭i 提交于 2019-12-10 14:24:01

问题


Why is set.begin() always returning a const iterator and not a standard one?

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’

回答1:


It's not returning a const_iterator, rather the key_type of std::set<int> is const int.

Remember that keys in a std::set are constant. You can't change a key after it's inserted into the set. So when you dereference the iterator, it necessarily returns a constant reference. So you need to say:

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


来源:https://stackoverflow.com/questions/4064841/strange-error-setintbegin-always-returning-const-iterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!