Search code examples
c++stringfor-loopstructured-bindings

Structured bindings on a map of string to string not working


This is my code:

std::map<std::string, std::string> map = {{"a","b"},{"c","d"}};
for(auto& [key,value] : map) {
    key = std::string("c");
    value = std::string("c");
}

and when i compile it i get

error: no viable overloaded '='

what i'm doing wrong? Shouldn't key and value be reference to string?


Solution

  • The key value in a std::map is a constant. Since the sort order of the map depends on the value of the key, if you change the key you'll probably break that ordering and have a node in the wrong place.

    In your code, key will be a const string &, while value will be a string & (so you can change the value).

    If you need to change the key for an entry in a map, you need to extract the value from the map, erase the original value, then re-insert the value using the new key.