Templates 707
19
In this example, a class is created and four students are added. The list of stu-
dents is then printed. After printing this list, Bill is printed along with his age;
however, rather than using a numeric indexer like previous example, Bill’s name is used
to find his age. This is made possible using the map template.
Digging into the code, you see that most of the listing is the Studentclass. This is code
you should be able to understand at this point.
The unique items in this listing start on line 2, where the header file <map>is included
because the standard mapcontainer class is being used. On line 73, you can see that a
prototype is provided for the ShowMapfunction. You can also see that this is a template
function. It is used to display the elements in a map.
On line 76,typedefis used to define SchoolClassas a map of elements; each consists
of a (key, value) pair. The first value in the pair is a string that is the key value. In this
example, for SchoolClass, the students’ names are this key value. The key value of ele-
ments in the map container must be unique; that is, no two elements can have the same
key value. The second value in the pair is the actual object, a Studentobject in the
example. The pair data type is implemented in the STL as a structof two members:
namely, first and second. These members can be used to access a node’s key and value.
You can take a look at the ShowMap()function on lines 103–111. The ShowMap()func-
tion uses a constant iterator to access a map object. On line 108,ci->firstpoints to the
key, or a student’s name. ci->secondpoints to the Studentobject.
All that remains to review in this listing is the main()function on lines 78–98. Back on
lines 80–83, four Studentobjects are created. The MathClassis defined as an instance
of our SchoolClasson line 85. On lines 86–89, the four students (actually the Student
objects) are added to the MathClassusing the following syntax:
map_object[key_value] = object_value;
On line 86, you can see that the key_value being used is the name from a Student
object. This name is obtained using the GetName()method from the Studentobject. The
object_value is a Studentobject.
The push_back()or insert()functions could also have been used to add a (key, value)
pair to the map; you can look up your compiler’s documentation for more details.
After all Studentobjects have been added to the map, you can access any of them using
their key values. On lines 94–96,MathClass[“Bill”]is used to retrieve Bill’s record.
Billis the key value. You could just as easily have used any of the other student’s names
to access their records.
ANALYSIS