0

Hi all,

I want to store some data pairs. A variable name and the value. I've try it in this way.

//data map testing
map<string, int> my_map;//map
map<string, int>::iterator my_it;//map iterator

my_map["first"]=10;
my_map["second"]=12;

string ss = "third";

my_it = my_map.find(ss);
if(my_it == my_map.end())
{
	//insert new value
	my_map["third"] = 15;
}
else
{
	//update the exsiting value
	my_map.erase(my_it);
}

I think my code is clear to you. Insert string,int pair. Before that I want to check that same string are in the map. If so I want to change the value only, with the existing one, not the variable name. Thats the point I've stuck. Can you guys give me a help on this.

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Narue
0

If I understand your problem correctly, you're over complicating things. The map container doesn't allow duplicates, and the subscript operator alone does what you want:

  • If the key doesn't exist, create a new pair and return a reference to the value.
  • If they key already exists, return a reference to the value.

You don't need to find and erase if the key exists, unless you're trying to do something other than what you've tried to explain.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.