If a std::map is const, then its values are constant too. For example, I can’t do this
void EditValue(const std::map<std::string, std::string>& m) {
std::string& value = m.at("mykey"); // <-- compile error
value.append("suffix");
}
But I could do this:
void EditValue(const std::map<std::string, std::string*>& m) {
std::string* value = m.at("mykey");
value->append("suffix"); // <-- this is fine
}
Is there no way to pass a non-pointer map and have only the values be mutable?
1
Yes, you can achieve this in C++ by using a const qualifier on the map’s key type while allowing the values to be mutable. This approach allows you to pass a map where the structure (i.e., the keys) is immutable, but the values can be changed.
Abdul Samad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.