Multimap constructors & destructors

Syntax:

    #include <map>
    multimap();
    multimap( const multimap& m );
    multimap( input_iterator start, input_iterator end );
    multimap( input_iterator start, input_iterator end, const key_compare& cmp );
    explicit multimap( const key_compare& cmp );
 
    ~multimap();

Multimaps have several constructors:

  • The default constructor takes no arguments, creates a new instance of that multimap, and runs in constant time.
  • The default copy constructor runs in linear time and can be used to create a new multimap that is a copy of the given multimap c.
  • Multimaps can also be created from a range of elements defined by start and end. When using this constructor, an optional comparison function cmp and allocator alloc can also be provided.

The default destructor is called when the multimap should be destroyed.

The template definition of multimaps requires that both a key type and value type be supplied. For example, you can instantiate a multimap that maps strings to integers with this statement:

    multimap<string,int> m;

You can also supply a comparison function and an allocator in the template:

    multimap<string,int,myComp,myAlloc> m;

For example, the following code uses a multimap to associate a series of employee names with numerical IDs:

    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. Note that the employee list is displayed in alphabetical order, because multimaps are sorted associative containers:

    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

Related Topics: count, insert z