Dave's Brain

Browse - 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; }

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.