insert

Syntax:

#include <map>
iterator insert( iterator pos, const TYPE& pair );
void insert( input_iterator start, input_iterator end );
pair<iterator,bool> insert( const TYPE& pair );

The function insert() either:

For example, the following code uses insert function (along with make_pair) to insert some data into a map, and then displays that data:

map<string,int> theMap;
theMap.insert( make_pair( "Key 1", -1 ) );
theMap.insert( make_pair( "Another key!", 32 ) );
theMap.insert( make_pair( "Key the Three", 66667 ) );
 
map<string,int>::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, the map is sorted alphabetically by key.

Related Topics: [] operator