[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: bitset Up: The Standard Library Previous: list

map

A map stores a mapping from one set of data (e.g. Names) to another (e.g. Phone numbers). The following example shows how to set up an ``associative array" - an array where you can use a string as an index. It records how many times each word appears on cin, the standard input.

int main()
{

string buf;
map<string, int> m;
while (cin>>buf) m[buf]++;
 // write out result (see next example)
}

A map keeps items in order and has no duplicate keys. Variations include

[fontsize=\small,frame=single,formatcom=\color{progcolor}]
// read in lines of the form 
//  red 7
//  blue 3
//  red 4

void readitems(map<string, int>& m)
{
  string word;
  int val=0;
      while(cin>>word>>val) m[word]+=val;
}

int main()
{
map<string, int>tbl;
readitems(tbl);
int total=0;
// We want to create an iterator p for use with this type of map.
// Since we're not going to change the map values using it,
// we'll make a const_iterator. We could do this using
//    map<string, int>::const_iterator p
// but if we wanted to create other iterators of this type
// it would be tedious. So we use 'typedef' to make 'CI' a
// shorthand for the long expression.

typedef map<string, int>::const_iterator CI;
   for (CI p=tbl.begin(); p!=tbl.end(); ++p) {
      total+=p->second;
      cout<<p->first << '\t' << p->second << '\n';
   }
   cout << "total\t" << total << endl;
   return !cin;
}

Here's a fragment using multimap showing how to print out all the values associated a particular key (in this case the string ``Gold"). It uses typedef as in the above example, and the useful equal_range function which returns an iterator to the first and last elements with a particular key value. Pairing up variables is so common that a facility called pair declared in the <utility> file is available to assist in their creation. The pair used here holds 2 iterators, but it can hold 2 items of different types too.

void f(multimap<string,int>&m)
{
typedef multimap<string, int>::iterator MI;
pair <MI,MI> g = m.equal_range("Gold");
   for (MI p=g.first; p!=g.second; ++p) {
      // print the value out
   }
}

In maps, m["blah"]=1; overwrites, m.insert(val) doesn't.


next up previous contents
Next: bitset Up: The Standard Library Previous: list
Tim Love
2001-07-05