Hi Experts,
I need to store some objects in a map. Then if 'needed' I have to modify the objects in the map and put them back.
Later, I am given an object which I have to compare with the objects in the map and see if it has been modified.
Can I modify the object and put it back. Or I need to remove the object to be modified and then put the modified object back to map?
The other question is how can I check if it is modified without doing a memberwise comparision?
typedef map<string, Test> myMap_t;
class MyMapClass{
public:
void insertToMap(string key, Test test);
bool isModifed(Test newTest);
private:
myMap_t m_myMap;
};
void MyMapClass::insertToMap( string key, Test test)
{
m_myMap.insert(myMap_t::value_type(std::string(key), test));
}
void MyMapClass::modify(string key )
{
// if we have an object for the key modify...
}
bool MyMapClass::isModifed(Test newTest)
{
//return true if it is modified else false
}
>>>> References are great for this.
You simply can do:
mymap[key] = data;
That works whether there is an existing (old) map element or not, cause mymap::operator[] creates a new data element for the given key if the element doesn't exist and returns a reference to it. If the element (key) exists it returns a reference to the existing data object. In both cases you can assign it to a temporary reference variable as rstaveley explained above.
mymap[key] = data;
Before using that statement you should set the proper contents to 'data' so that you don't need to make further calls to the object stored in the map. Doing so has the advantage over operating with a local reference that the object, where mymap[key] is a reference of, is complete if data is complete. That is cause mymap[key] might be uninitialized if there is no valid default constructor.
Regards, Alex