Tuesday, October 27, 2009

25.4 Storing Grades in a STL Map




I l@ve RuBoard










25.4 Storing Grades in a STL Map



Let's change our class roster so that
we





record not only the name of each student, but also the
student's grade as well. We do this using something
called a map. To define our class map, we use the
following declaration:



#include <map>

// Map key=name(string), value = grade(char)
template map<string, char> student_roster;


Inserting an item into a map is a little trickier
that inserting one into a set because we are
inserting a pair of items. The STL handles this nicely by providing a
pair class that takes two elements and turns them
into an item that a map can handle. For example, if John Smith is in
the class and got an A, we would write:



    student_roster(pair(string("John Smith"), 'A'));


Suppose we want to find out what Mr. Smith's grade
is. We can search for his record using the find
function call. It takes three parameters: a place to start the
search, a place to end the search, and something to look for. It
returns an iterator pointing to the item found or, if nothing is
found, the value returned by the end function. To
look for Mr. Smith's grade, we use the code:



    map<string, char>::const_iterator record_loc;

record_loc = find(student_roster.begin(), student_roster.end( );
string("John Smith"));


Now let's check to see if we found the student:



    if (record_loc == student_roster.end(  ))
std::cerr << "John Smith not found in the class\n";


The iterator points to a pair consisting of the
student's name and grade. The fields of a
pair are named first and
second. To print John's record,
we use the statement:



    std::cout << "Student: " << record_loc->first << " Grade:" << 
record_loc->second << '\n';








    I l@ve RuBoard



    No comments: