insert [C++ Reference]
Keywords: stl,multimap,insert
Date: 2008-10-14T15:42:07-0700

## insert

Syntax:

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

The function insert() either:

- inserts val after the element at pos (where pos is really just a suggestion as to where val should go, since multimaps are ordered), and returns an iterator to that element.
- inserts val into the multimap, returning an iterator to the element inserted.
- inserts a range of elements from start to end.

For example, the following code uses the insert() function to add several <name,ID> pairs to a employee multimap:

        multimap<string,int> m;

        int employeeID = 0;
        m.insert( pair<string,int>("Bob Smith",employeeID++) );
        m.insert( pair<string,int>("Bob Thompson",employeeID++) );
        m.insert( pair<string,int>("Bob Smithey",employeeID++) );
        m.insert( pair<string,int>("Bob Smith",employeeID++) );

        cout << "Number of employees named 'Bob Smith': " << m.count("Bob Smith") << endl;
        cout << "Number of employees named 'Bob Thompson': " << m.count("Bob Thompson") << endl;
        cout << "Number of employees named 'Bob Smithey': " << m.count("Bob Smithey") << endl;

        cout << "Employee list: " << endl;
        for( multimap<string, int>::iterator iter = m.begin(); iter != m.end(); ++iter ) {
          cout << " Name: " << iter->first << ", ID #" << iter->second << endl;
        }

When run, the above code produces the following output:

      Number of employees named 'Bob Smith': 2
      Number of employees named 'Bob Thompson': 1
      Number of employees named 'Bob Smithey': 1
      Employee list:
       Name: Bob Smith, ID #0
       Name: Bob Smith, ID #3
       Name: Bob Smithey, ID #2
       Name: Bob Thompson, ID #1