Sign in to follow this  
tonyaim83

Problem in inserting values in map

Recommended Posts

Hi My current problem stmt is :- There are n no. of cities each having unique name and each city having m no. of streets. I have all the information as in which street belong to which city and so on. I'm able to extract information from the given input file using the function GetName now i want to store this information in some data structure. My current implementation goes like [Code] .... string CityName; string StreetName; GetName(CityName,StreetName); typedef vector<string> StrName; map<string,StrName>cityMap; map<string,StreetName>::iterator iterMap; iterMap=cityMap.find(CityName); if(iterMap==cityMap.end()) { cityMap.insert((std::make_pair(CityName,StrName.push_back(StreetName))); } else { //I want to insert value to the corresponding cityname or the returned iterator } [/Code] I'm getting compilation error while i'm trying to insert the value. Also once the values are inserted i need to retrieve them using simple for loop.How to do that in this case. Kindly help

Share this post


Link to post
Share on other sites
I m able to remove the compilation now.But still i have problem in inserting values for the cities whose name is already existing.
[Code=c++]
....
string CityName;
string StreetName;
GetName(CityName,StreetName);
typedef vector<string> StrName;
map<string,StrName>cityMap;
map<string,StreetName>::iterator iterMap;
iterMap=cityMap.find(CityName);
if(iterMap==cityMap.end())
{
StrName.clear();
StrName.push_back(StreetName);
cityMap.insert((std::make_pair(CityName,StrName)));
}
else
{
//I want to insert value to the corresponding cityname or the returned iterator
}

[/code]

How to write code for the else part

Share this post


Link to post
Share on other sites
The potentially missing piece of information: iterators are used just like pointers, so 'it->second' refers to the vector found in the map.

But really, you are making this too complicated. The operator[] of the map does exactly what you want:


string CityName;
string StreetName;
GetName(CityName, StreetName);
typedef vector<string> StrName;
map<string, StrName> cityMap;

cityMap[CityName].push_back(StreetName);

// If the CityName is not found, the operator[] will automatically insert it
// with a default-constructed value (i.e. an empty vector). Then it returns a
// reference to the value (whether it was already there, or just created now).
// So we just add the StreetName to that vector; in either case, it does what
// we want.


(BTW, the forum "code" tag needs to be in lowercase.)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this