Associative Arrays in C++ - Map(C++)

An Example

The following C++ program uses associative arrays to count how many times each distinct word occurs in its input:

   #include <String.h>
   #include <Map.h>
   #include <iostream.h>

main() { Map<String,int> count; String word;

while (cin >> word) count[word]++;

cout << count << endl; }

The #include statements bring in declarations for the string, associative array, and input-output packages, respectively.

The first declaration in the main program defines count to be of type Map<String,int>.

The program does most of its work in the first loop. It reads each word from its input into word and increments the corresponding element of count. Trying to increment a non-existent element automatically creates the element first and gives it an initial value of 0. This value is almost immediately incremented to 1.

When the input is exhausted, the first loop finishes. All the information we need is now in count; we need merely print it. Here is the result of giving a copy of this program as input to itself:

   {[ #include 3 ][ (cin 1 ][ << 2 ][ <Map.h> 1 ]
   [ <String.h> 1 ][ <stream.h> 1 ][ >> 1 ]
   [ Map<String,int> 1 ] [ String 1 ][ count 1 ][ count; 1 ]
   [ count[word]++; 1 ][ cout 1 ][ endl; 1 ][ main() 1 ]
   [ while 1 ][ word) 1 ][ word; 1 ][ { 1 ][ } 1 ]}

(For an example of how to produce prettier output for this example, see ``Iterators'' below.) The program is obviously naive about the role of punctuation, but the output is otherwise about what one would expect. Notice especially that the output is sorted by key. The ordering, of course, depends on the particular C++ implementation's collating sequence for character strings.

Next topic: Defining Map Classes
Previous topic: Introduction

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