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

Using a Map

Indexing is the fundamental map operation: if m is of type Map<K,V> and x is of type K, then m[x] is an lvalue of type V. Thus we store a value v in m[x] by writing:

   m[x] = v;

and retrieve it again by writing:

   v = m[x];

If we ask for the value of m[x] without ever having specified one, we get the "default value" of type V: the value of an otherwise uninitialized static variable of type V It is very important that this is the value of a static variable in case V is a built-in type: the default value of an ordinary int variable is undefined but static int variables are initialized to zero. Thus after executing:

   Map<String,int> m;
   

m["Morristown"]++;

m has one element with key Morristown and value 1.

Because evaluating m[k] creates an element of m if an appropriate element does not already exist, we need a way to test whether an element exists without creating one. Thus every map has a member function called element which returns an appropriate value:

   if (m.element(k))
           // m[k]  exists

Thus if we did not wish to rely on default values for map elements, we could write:

   if (m.element(word))
           m[word]++;
   else
           m[word] = 1;

The number of elements in a map m is m.size().

We can explicitly nominate a default value for map elements by passing that value to the map constructor. For example:

   Map<String,String> s ("(undefined)");

declares s to be a map in which keys and values are both of type String and in which element values are initially (undefined).

A map entry can be removed from the map:

   m.remove("Newark");

The element with the given key value is removed from the map. If there is no entry in the map that has this key, there is no effect.


Next topic: Copying a Map
Previous topic: Key and Value Types

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005