DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Associative Arrays in C++ - Map(3C++)

Suggested Applications

Although a map is not a good replacement for a conventional array when time is critical, time is often not critical. For example, we have seen many programs that use conventional arrays to build up an array of arguments to hand to some system command or other utility routine. The usual approach is to make the array some arbitrary size and then either not check for overflow (so that the program aborts unpredictably when overflow occurs) or check for it and terminate the program explicitly.

A map can often be used in this context as if it were a conventional array of unbounded size. Even if the utility being called demands a conventional array as its input, it is possible to use the size function to allocate the right amount of memory at the last minute and then copy the elements. This approach may waste some machine resources, but the waste is often negligible compared to the execution time of the utility itself and carries a compensating gain in generality and robustness.

Maps are a good candidate for use in compiler symbol tables. In particular, it is unnecessary to sort such a symbol table in order to print a cross-reference listing.

The value of a map element can itself be a map (use typedef to get around the single-identifier restriction). If m is such a map, m[k1][k2] has the expected meaning: m[k1] is the map that is the value of the element of m with key k1, and m[k1][k2] is the value of the element of m[k1] with key k2.


Next topic: Implementation Notes and Warnings
Previous topic: Performance

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004