insert

C/C++ Reference

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

The function insert() either:

  • 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<key,val>, 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 the insert() function (along with the make_pair() function) 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: