Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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’
like image 473
I-man Avatar asked Oct 31 '10 19:10

I-man


1 Answers

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();
like image 149
Charles Salvia Avatar answered Nov 09 '22 01:11

Charles Salvia