Understanding Associative Containers ..........................................................
You have seen that a vector is like an enhanced version of an array. It has all the charac-
teristics of an array and some additional features. Unfortunately, the vector also suffers
from one of the significant weaknesses of arrays: You cannot find an element using any
index other than its offset in the container. Associative containers, on the other hand, pro-
vide fast random access based on keysthat are associated with values.
The sequence containers are designed for sequential and random access of elements
using the index or an iterator, the associative containers are designed for fast random
access of elements using keys. The Standard C++ Library provides five associative con-
tainers:map,multimap,set,multiset, and bitset.
The Map Container
The first associate container you will learn about is the map. The name comes from the
idea that they contain “maps,” which are the key to the associated value, just as a point
on a paper map corresponds to a real place on earth. In the following example (Listing
19.10), a map is used to implement the school class example shown in Listing 19.8.
LISTING19.10 A Map Container Class
0: #include <iostream>
1: #include <string>
2: #include <map>
3: using namespace std;
4:
5: class Student
6: {
7: public:
8: Student();
9: Student(const string& name, const int age);
10: Student(const Student& rhs);
11: ~Student();
12:
13: void SetName(const string& name);
14: string GetName() const;
15: void SetAge(const int age);
16: int GetAge() const;
17:
18: Student& operator=(const Student& rhs);
19:
20: private:
21: string itsName;
22: int itsAge;
23: };
24:
704 Day 19