Monday, November 28, 2011

stl map

Examples of Using Maps and Multimaps / stl map c++

The elements of maps and multimaps are key/value pairs. Thus, the  declaration, the insertion, and the access to elements are a bit different. Here is an example of using a multimap:

The program may have the following output:

this is a multimap of tagged strings However, because "this" and  "is" have the same key, their order might be the other way around.

When you compare this example with the set example presented earlier, you can see the following two differences:
  1. The elements are key/value pairs, so you must create such a pair to insert it into the collection. The auxiliary function make_pair() is provided for this purpose.  
  2. The iterators refer to key/value pairs. Therefore, you can't just print them as a whole. Instead, you must access the members of the pair structure, which are called first and second. Thus, the expression "pos->second" yields the second part of the key/value pair, which is the value of the multimap element. As with ordinary pointers, the expression is defined as an abbreviation for
Note: In some older environments, operator -> might not work yet  or iterators. In this case, you must use the second version. (*pos) .second 

Similarly, the expression


yields the first part of the key/value pair, which is the key of  the multimap element.

Multimaps can also be used as dictionaries.

See Also:

No comments:

Post a Comment