Thursday, July 12, 2012

Stl containers

1. Map's insert
Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.


Thus, below code's output will be 2 instead of 3.




    map<int, int> iMap;
    iMap.insert(map<int, int>::value_type(1, 2));


    map<int, int>::iterator it = iMap.find(1);
    if (it != iMap.end())
    {
        iMap.insert(map<int, int>::value_type(1, 3));
        it = iMap.find(1);
        if (it != iMap.end())
        {
            cout << it->second << endl;
        }
    }


Something additional is its return value:
returns a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the element that already had its same key in the map. The pair::second element in the pair is set totrue if a new element was inserted or false if an element with the same key existed.


It means you can use its return value's second to check if this insertion is a success or not.



No comments:

Post a Comment