// Program to demonstrate sorting and searching of personnel records,
// showing how to define a function object that tells how to compare two
// such records.
#include <mstring.h>
#include <vector.h>
#include <algo.h>
struct person {
string first_name;
string last_name;
int number;
};
void output(const person& record)
{
cout << record.first_name << " " << record.last_name
<< ", Record No. " << record.number << "\n";
}
int rec_no = 1; // shouldn't really be a global variable
void read_names(vector<person>& roster)
{
person person1;
while (true) {
cin >> person1.first_name;
if (person1.first_name == string("---"))
break;
cin >> person1.last_name;
person1.number = rec_no++;
roster.push_back(person1); // put person1 at end of roster
}
}
// Following is a function object type,
// defines how to compare persons (for sorting/searching)
struct NameCompare {
bool operator()(const person& a, const person& b) {
return a.last_name < b.last_name; // based on last names only
}
};
NameCompare nameComp; /* declare a comparison function object, to
pass to sort and search algorithms */
int main()
{
vector<person> roster;
read_names(roster);
sort(roster.begin(), roster.end(), nameComp);
cout << "Current persons, listed alphabetically by last name:\n\n";
for (vector<person>::iterator i = roster.begin();
i != roster.end(); ++i)
output(*i);
cout << "\n\n";
person search_record;
while (true) {
cin >> search_record.last_name;
if (search_record.last_name == string("---"))
break;
cout << "Searching for a person named "
<< search_record.last_name << "...\n";
i = lower_bound(roster.begin(), roster.end(),
search_record, nameComp);
if ((*i).last_name == search_record.last_name) {
cout << "Found ";
output(*i);
cout << "\n";
} else
cout << "Sorry, there's no record of a person named "
<< search_record.last_name << "\n\n";
}
return 0;
}