Syntax:
#include <map> multimap(); multimap( const multimap& c ); multimap( iterator begin, iterator end, const key_compare& cmp = Compare(), const allocator& alloc = Allocator() ); ~multimap();
Multimaps have several constructors:
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