Can the datatype of the value(not the key) be a struct with 2 different integers(parent and child)? If yes how do I access the the parent or child element using the map. Thanks
struct{
int parent;
int child;};
Be aware that the operator[] for std::map will default construct a key/value pair if the specified key wasn't found. A lot of times we use the map::find to search for an existing key. Then we check the iterator to see if it is equal to the end iterator. If not then we use the iterator to access the value. I did not test this code but it should give you the general idea.
1 2 3 4 5 6 7 8 9 10 11 12
MyMapType::iterator pos = myMap.find(key);
if(pos != myMap.end())
{
// found something
cout << "key: " << key << " found in the map!"
<< "value: " << (pos->second).parent << " , " << (pos->second).child << endl;
}
else
{
// key didn't exist
cout << "key: " << key << " doesn't exist in the map!" << endl;
}
If I want to increment a value of the parent by 1.
Can I do (map[key].parent)++ ?
what about incrementing by 2
map[key].parent = map[key].parent + 2 is ok?