stl map value datatype

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;};
map[key].parent
map[key].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;
}
And can I initialize it as map<int,tree> sourcePoints;
where tree is given by
struct tree{
int parent;
int child;}
;
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?
vkaul1 wrote:
And can I initialize it as map<int,tree> sourcePoints;

Yes, that's how you should declare it.

vkaul1 wrote:
If I want to increment a value of the parent by 1.
Can I do (map[key].parent)++ ?

Yes. You can also omit the parentheses.

vkaul1 wrote:
what about incrementing by 2
map[key].parent = map[key].parent + 2 is ok?

Yes. map[key].parent+=2; should be ok too.
Why don't you just write some code and try these things? read the documentation on std::map and write a practice program.
Why don't you just write some code and try these things? read the documentation on std::map and write a practice program.


+1
Topic archived. No new replies allowed.