Storing User-Defined Objects. Sams Publishing Object-Oriented Programming in C++
Below you will find brief information for Object-Oriented Programming in C++. This book provides a comprehensive guide to object-oriented programming principles and techniques, using the C++ language. It covers topics such as classes, objects, inheritance, polymorphism, templates, and the Standard Template Library (STL).
Advertisement
Advertisement
16 3087 CH15 11/29/01 2:16 PM Page 778
778
Chapter 15
The definition of a map takes three template arguments: map<string, int, less<string> > maStates;
The first is the type of the key. In this case it’s string
, representing the state name. The second is the type of the value; in this case it’s int
, which represents the population, in 1,000s. The third argument specifies the ordering that will be used for the keys. We choose to have it ordered alphabetically by the names of the states; that’s what less<string> does. We also define an iterator to this map.
Our input data is in two separate arrays. (In a real program it would probably come from a file.) To put this data into the map we read it into the variables name and pop
, and execute the statement mapStates[name] = pop;
This is a particularly elegant construction, looking just like an insertion into an ordinary array.
However, the array index name is a string, not an integer.
When the user types in a state name, the program finds the appropriate population with the statement pop = mapStates[name];
Besides using the array-index syntax, we can also access the two parts of an entry in the map, the key, and the value, using an iterator. The key is obtained from
(*iter).first
, and the value from
(*iter).second
. Otherwise the iterator works as it does in other containers.
Storing User-Defined Objects
Until now our example programs have stored objects of basic types. However, the big payoff with the STL is that you can use it to store and manipulate objects of classes that you write yourself (or that someone else has written). In this section we’ll show how this is done.
A Set of
person
Objects
We’ll start with a person class that includes a person’s last name, first name, and telephone number. We’ll create some members of this class and insert them in a set, thus creating a phone book database. The user interacts with the program by entering a person’s name. The program then searches the list and displays the data for that person, if it finds a match. We’ll use a multiset so two or more person objects can have the same name. Here’s the listing for
SETPERS
:
// setpers.cpp
// uses a multiset to hold person objects
#pragma warning (disable:4786) //for set (Microsoft only)
#include <iostream>
16 3087 CH15 11/29/01 2:16 PM Page 779
The Standard Template Library
779
#include <set>
#include <string> using namespace std; class person
{ private: string lastName; string firstName; long phoneNumber; public: //default constructor person() : lastName(“blank”), firstName(“blank”), phoneNumber(0)
{ }
//3-arg constructor person(string lana, string fina, long pho) : lastName(lana), firstName(fina), phoneNumber(pho)
{ } friend bool operator<(const person&, const person&); friend bool operator==(const person&, const person&); void display() const //display person’s data
{ cout << endl << lastName << “,\t” << firstName
<< “\t\tPhone: “ << phoneNumber;
}
};
//operator < for person class bool operator<(const person& p1, const person& p2)
{ if(p1.lastName == p2.lastName) return (p1.firstName < p2.firstName) ? true : false; return (p1.lastName < p2.lastName) ? true : false;
}
//operator == for person class bool operator==(const person& p1, const person& p2)
{ return (p1.lastName == p2.lastName && p1.firstName == p2.firstName ) ? true : false;
}
//////////////////////////////////////////////////////////////// int main()
{ //create person objects person pers1(“Deauville”, “William”, 8435150); person pers2(“McDonald”, “Stacey”, 3327563); person pers3(“Bartoski”, “Peter”, 6946473); person pers4(“KuangThu”, “Bruce”, 4157300);
15
16 3087 CH15 11/29/01 2:16 PM Page 780
780
Chapter 15 person pers5(“Wellington”, “John”, 9207404); person pers6(“McDonald”, “Amanda”, 8435150); person pers7(“Fredericks”, “Roger”, 7049982); person pers8(“McDonald”, “Stacey”, 7764987);
//multiset of persons multiset< person, less<person> > persSet;
//iterator to a multiset of persons multiset<person, less<person> >::iterator iter; persSet.insert(pers1); //put persons in multiset persSet.insert(pers2); persSet.insert(pers3); persSet.insert(pers4); persSet.insert(pers5); persSet.insert(pers6); persSet.insert(pers7); persSet.insert(pers8); cout << “\nNumber of entries = “ << persSet.size(); iter = persSet.begin(); //display contents of multiset while( iter != persSet.end() )
(*iter++).display();
//get last and first name string searchLastName, searchFirstName; cout << “\n\nEnter last name of person to search for: “; cin >> searchLastName; cout << “Enter first name: “; cin >> searchFirstName;
//create person with this name person searchPerson(searchLastName, searchFirstName, 0);
//get count of such persons int cntPersons = persSet.count(searchPerson); cout << “Number of persons with this name = “ << cntPersons;
//display all matches iter = persSet.lower_bound(searchPerson); while( iter != persSet.upper_bound(searchPerson) )
(*iter++).display(); cout << endl; return 0;
} //end main()
16 3087 CH15 11/29/01 2:16 PM Page 781
The Standard Template Library
781
Necessary Member Functions
To work with STL containers, the person class needs a few common member functions. These are a default (no-argument) constructor (which is actually not necessary in this example but is usually essential), the overloaded
< operator, and the overloaded
== operator. These member functions are used by the list class and by various algorithms. You may need other member functions in other specific situations. (As in most classes, you should probably also provide overloaded assignment and copy constructors and a destructor, but we’ll ignore these here to avoid complicating the listing.)
The overloaded
< and
== operators should use const arguments. Generally it’s best to make them friends
, but you can use member functions as well.
Ordering
The overloaded
< operator specifies the way the elements in the set will be ordered. In
SETPERS we define this operator to order the last name of the person, and, if the last names are the same, to order the first names.
Here’s some interaction with
SETPERS
. The program first displays the entire list. (Of course this would not be practical on a real database with a large number of elements.) Because they are stored in a multiset, the elements are ordered automatically. Then, at the prompt, the user enters the name “McDonald” followed by “Stacey” (last name first). There are two persons on the list with this particular name, so they are both displayed.
Number of entries = 8
Bartoski, Peter phone: 6946473
Deauville, William phone: 8435150
Fredericks, Roger phone: 7049982
KuangThu, Bruce phone: 4157300
McDonald, Amanda phone: 8435150
McDonald, Stacey phone: 3327563
McDonald, Stacey phone: 7764987
Wellington, John phone: 9207404
Enter last name of person to search for: McDonald
Enter first name: Stacey
Number of persons with this name = 2
McDonald, Stacey phone: 3327563
McDonald, Stacey phone: 7764987
Just Like Basic Types
As you can see, once a class has been defined, objects of that class are handled by the container in the same way as variables of basic types.
We first use the size() member function to display the total number of entries. Then we iterate through the list, displaying all the entries.
15
16 3087 CH15 11/29/01 2:16 PM Page 782
782
Chapter 15
Because we’re using a multiset, the lower_bound() and upper_bound() member functions are available to display all elements that fall within a range. In the example output the lower and upper bound are the same, so all persons with the same name are displayed. Notice that we must create a “fictitious” person with the same name as the person (or persons) we want to find. The lower_bound() and upper_bound() functions then match this person against those on the list.
A List of
person
Objects
It’s very fast to search a set or multiset for a person with a given name, as in the
SETPERS example. If, however, we’re more concerned with being able to quickly insert or delete a person object, we might decide to use a list instead. The
LISTPERS example shows how this looks.
// listpers.cpp
// uses a list to hold person objects
#include <iostream>
#include <list>
#include <algorithm>
#include <string> using namespace std; class person
{ private: string lastName; string firstName; long phoneNumber; public: person() : //no-arg constructor lastName(“blank”), firstName(“blank”), phoneNumber(0L)
{ }
//3-arg constructor person(string lana, string fina, long pho) : lastName(lana), firstName(fina), phoneNumber(pho)
{ } friend bool operator<(const person&, const person&); friend bool operator==(const person&, const person&); friend bool operator!=(const person&, const person&); friend bool operator>(const person&, const person&); void display() const //display all data
{ cout << endl << lastName << “,\t” << firstName
<< “\t\tPhone: “ << phoneNumber;
}
16 3087 CH15 11/29/01 2:16 PM Page 783
The Standard Template Library
783 long get_phone() const //return phone number
{ return phoneNumber; }
};
//overloaded == for person class bool operator==(const person& p1, const person& p2)
{ return (p1.lastName == p2.lastName && p1.firstName == p2.firstName ) ? true : false;
}
//overloaded < for person class bool operator<(const person& p1, const person& p2)
{ if(p1.lastName == p2.lastName) return (p1.firstName < p2.firstName) ? true : false; return (p1.lastName < p2.lastName) ? true : false;
}
//overloaded != for person class bool operator!=(const person& p1, const person& p2)
{ return !(p1==p2); }
//overloaded > for person class bool operator>(const person& p1, const person& p2)
{ return !(p1<p2) && !(p1==p2); }
//////////////////////////////////////////////////////////////// int main()
{ list<person> persList; //list of persons
//iterator to a list of persons list<person>::iterator iter1;
//put persons in list persList.push_back( person(“Deauville”, “William”, 8435150) ); persList.push_back( person(“McDonald”, “Stacey”, 3327563) ); persList.push_back( person(“Bartoski”, “Peter”, 6946473) ); persList.push_back( person(“KuangThu”, “Bruce”, 4157300) ); persList.push_back( person(“Wellington”, “John”, 9207404) ); persList.push_back( person(“McDonald”, “Amanda”, 8435150) ); persList.push_back( person(“Fredericks”, “Roger”, 7049982) ); persList.push_back( person(“McDonald”, “Stacey”, 7764987) ); cout << “\nNumber of entries = “ << persList.size(); iter1 = persList.begin(); //display contents of list while( iter1 != persList.end() )
(*iter1++).display();
//find person or persons with specified name (last and first) string searchLastName, searchFirstName;
15
16 3087 CH15 11/29/01 2:16 PM Page 784
784
Chapter 15 cout << “\n\nEnter last name of person to search for: “; cin >> searchLastName; cout << “Enter first name: “; cin >> searchFirstName;
//make a person with that name person searchPerson(searchLastName, searchFirstName, 0L);
//search for first match of names iter1 = find(persList.begin(), persList.end(), searchPerson); if( iter1 != persList.end() ) //find additional matches
{ cout << “Person(s) with that name is(are)”; do
{
(*iter1).display(); //display match
++iter1; //search again, one past match iter1 = find(iter1, persList.end(), searchPerson);
} while( iter1 != persList.end() );
} else cout << “There is no person with that name.”;
//find person or persons with specified phone number cout << “\n\nEnter phone number (format 1234567): “; long sNumber; //get search number cin >> sNumber;
//iterate through list bool found_one = false; for(iter1=persList.begin(); iter1 != persList.end(); ++iter1)
{ if( sNumber == (*iter1).get_phone() ) //compare numbers
{ if( !found_one )
{ cout << “Person(s) with that phone number is(are)”; found_one = true;
}
(*iter1).display(); //display the match
}
} //end for if( !found_one ) cout << “There is no person with that phone number”; cout << endl; return 0;
} //end main()
16 3087 CH15 11/29/01 2:16 PM Page 785
The Standard Template Library
785
Finding All Persons with a Specified Name
We can’t use the lower_bound()
/ upper_bound() member functions because we’re dealing with a list, not a set or map. Instead we use the find() member function to find all the persons with a given name. If this function reports a hit, we must apply it again, starting one person past the original hit, to see whether there are other persons with the same name. This complicates the programming; we must use a loop and two calls to find()
.
Finding All Persons with a Specified Phone Number
It’s harder to search for a person with a specified phone number than one with a specified name, because the class member functions such as find() are intended to be used to find the primary search characteristic. In this example we use the brute force approach to finding the phone number, iterating through the list and making a “manual” comparison of the number we’re looking for and each member of the list: if( sNumber == (*iter1).getphone() )
...
The program first displays all the entries, then asks the user for a name and finds the matching person or persons. It then asks for a phone number and again finds any matching persons.
Here’s some interaction with
LISTPERS
:
Number of entries = 8
Deauville, William phone: 8435150
McDonald, Stacey phone: 3327563
Bartoski, Peter phone: 6946473
KuangThu, Bruce phone: 4157300
Wellington, John phone: 9207404
McDonald, Amanda phone: 8435150
Fredericks, Roger phone: 7049982
McDonald, Stacey phone: 7764987
Enter last name of person to search for: Wellington
Enter first name: John
Person(s) with that name is(are)
Wellington, John phone: 9207404
Enter phone number (format 1234567): 8435150
Person(s) with that number is(are)
Deauville, William phone: 8435150
McDonald, Amanda phone: 8435150
Here the program has found one person with the specified name and two people with the specified phone number.
15
Download
Advertisement
Key features
Comprehensive coverage of OOP principles
Practical examples and exercises
Focus on C++ implementation
Explanation of STL and templates
Frequently asked questions
This book covers the object-oriented programming paradigm.
The book primarily uses the C++ programming language.
Yes, the book includes a section on the Standard Template Library (STL).