Programming Tips - How can I rename a std::map key?

Date: 2009oct21 Language: C/C++ Q. How can I rename a std::map<> key? A. Assuming these declarations:
typedef std::map<std::string, int, std::less<std::string> > StringToInt; StringToInt m;
You might first try this:
StringToInt::iterator it; it = m.find("something"); it->first = "something else"; // WRONG!!!
This doesn't work because it->first is a const. So do this:
bool rename_key(const std::string old_key, const std::string new_key) { StringToInt::iterator it; if ((it = m.find(old_key)) == m.end()) return false; m.insert(StringToInt::value_type(new_key, it->second)); m.erase(it); return true; }