简体   繁体   中英

Error binding 'string&' to 'const string' when dereferencing a set iterator

I'm using C++11 and STL. I have this piece of code:

std::set<std::string>::iterator it;
[...]
std::string &str = *it;

Compiler throws this error:

error: binding reference of type 'std::__cxx11::string& {aka std::__cxx11::basic_string&}' to 'const std::__cxx11::basic_string' discards qualifiers

Why is it happening?

The keys in a set or map are const. If they were not, the set would not be able to provide its guarantee that elements are weakly ordered on the key. ie the would become inexplicably unsorted when users mutated the keys.

The std::set iterator dereferences to a key. Keys are (to reiterate) const.

Mutable references cannot bind to const references (language-imposed rule).

Therefore, either:

std::string const& str = *it;   // refer to the key

or

std::string str = *it;          // take a copy of the key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM