=====insert=========
Syntax:
#include
There are three versions of the ''insert'' method for maps:
- inserts ''pair'' after the element at ''pos'' (where ''pos'' is really just a suggestion as to where ''pair'' should go, since sets and maps are ordered), and returns an iterator to that element.
- inserts a range of elements from ''start'' to ''end''.
- inserts ''pair'', but only if no element with key ''key'' already exists. The return value is an iterator to the element inserted (or an existing pair with key ''key''), and a boolean which is true if an insertion took place.
For example, the following code uses insert function (along with [[stl/utility/make_pair]]) to insert some data into a map, and then displays that data:
map theMap;
theMap.insert( make_pair( "Key 1", -1 ) );
theMap.insert( make_pair( "Another key!", 32 ) );
theMap.insert( make_pair( "Key the Three", 66667 ) );
map::iterator iter;
for( iter = theMap.begin(); iter != theMap.end(); ++iter ) {
cout << "Key: '" << iter->first << "', Value: " << iter->second << endl;
}
When run, the above code displays this output:
Key: 'Another key!', Value: 32
Key: 'Key 1', Value: -1
Key: 'Key the Three', Value: 66667
Note that because maps are sorted containers, the output is sorted by the key
value. In this case, since the map key data type is [[string/|string]], the map is sorted
alphabetically by key.
Related Topics: [[map_operators|[] operator]]