Map size: 5 Charlie M.: 3374 David D.: 1923 John A.: 7582 Mike C.: 5234 Peter Q.: 5328
Note: The fully defined STL map defines a comparison operator in the map declaration so that the indexes can be ordered. This is used to provide a default comparison operator for the data type. In the above example, the key type is an integer and the C++ "equals" (=) and "less than" operator (<) can operate on an integer so the example works. The use of the STL algorithm std::less<> can be specified explicitly as in the following declaration:
std::map<int, string, std::less< int > >
If
defining your own class as the index (first value), C++ will not know how to perform the comparison, thus you will have to provide an operator to perform this function.
The first element in a map can be a class or even another STL container such as a pair. If using a class, the class must provide an overloaded "equals" (=) and "less than" operator (<).
Thus using "char" instead of "string" requires the use of a comparison function:
01
#include <string.h>
02
#include <iostream>
03
#include <map>
04
#include <utility>
05
06
usingnamespacestd;
07
08
structcmp_str
09
{
10
booloperator()(char const*a, charconst*b)
11
{
12
returnstd::strcmp(a, b) < 0;
13
}
14
};
15
16
intmain()
17
{
18
map<char*, int, cmp_str> Employees;
19
20
// Examples of assigning Map container contents
21
22
// 1) Assignment using array index notation
23
Employees["Mike C."] = 5234;
24
Employees["Charlie M."] = 3374;
25
26
// 2) Assignment using member function insert() and STL pair
Number of elements with key a: 2
Number of elements with key b: 3
Number of elements with key c: 1
Elements in m:
[a, 1]
[a, 5]
[b, 3]
[b, 4]
[b, 6]
[c, 2]
Range of "b" elements:
[b, 3]
[b, 4]
[b, 6]