Dave's Brain

Browse - programming tips - stl map rename 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;
	}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, 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.