coolDude
coolDude

Reputation: 43

How to updating the objects of a map in C++

I have a map which has a bunch of integers,vector and a map.

class testMap
{
    int var1;
    int var2;
    ........
    .......
    int var50; //variables up to 50
    map  objmap;
    int *ptr
    vector<myClass> vecObj; //vector of myClass objects
}
typedef std::map<string , testMap> eeMap; //global map
eeMap tMap;

Assuming I created add one entry using map insert tMap.insert(make_pair ("test", *ptrTestMap ) ); how do I update the object in this global map via a function.

This new object might have only one variable changed or it can be multiple.

void UpdateTestMap(testMap newTestMapValue,string key)
{

//enter code here

}

Option#1: Have a overloaded assignment operator 
Option#2 Compare the members one by one and overwrite the variables that are changed.
Option#3 Erase the key and insert it again with the same key and the new object.
##Any other option

I appreciate what would be the best option of doing this?.

Upvotes: 1

Views: 1580

Answers (2)

lewohart
lewohart

Reputation: 97

In this code the "tMap" is a type not an instance. You cannot add with "tMap.insert". First declare the global map like this:

tMap globalMap;

Then add values with:

globalMap.insert(make_pair ("test", *ptrTestMap ) );

And change values simple with [] std::map operator:

globalMap[key] = newMapValue;

Upvotes: 1

ciprianr
ciprianr

Reputation: 309

As the question stands you do not seem to want to change the key, so it's pretty simple

void UpdateTestMap(testMap& newTestMapValue,string key)
{
     //tMap.erase(key); - as per the comment below this is not needed

     tMap[key] = newTestMapValue;

}

Seems simple and does what you seem to want

Upvotes: 1

Related Questions