// 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 #include #include using namespace std;; int const LENGTH = 30; struct Person { char firstName[LENGTH]; char lastName[LENGTH]; int number; }; //-------------------------- output ---------------------------------------- void output(const Person& record) { cout << record.firstName << " " << record.lastName << ", Record No. " << record.number << endl; } //-------------------------- readNames ------------------------------------ void readNames(vector& roster) { Person thePerson; int recNum = 1; for (;;) { cout << "Enter first name (--- to stop): "; cin >> thePerson.firstName; if (strcmp(thePerson.firstName, "---") == 0) break; cout << "Enter last name: "; cin >> thePerson.lastName; thePerson.number = recNum++; roster.push_back(thePerson); // put thePerson at end of roster } } //--------------------------- operator() ----------------------------------- // Following is a function object type, // defines how to compare persons (for sorting/searching) struct NameCompare { bool operator()(const Person& a, const Person& b) const { return strcmp(a.lastName, b.lastName) < 0; // based on last names only } }; //----------------------------- main --------------------------------------- int main() { // a comparison function object, used for sorting and searching NameCompare nameComp; // fill and sort a vector of Persons vector roster; readNames(roster); sort(roster.begin(), roster.end(), nameComp); // display the list alphabetically cout << "Current persons, listed alphabetically by last name:" << endl; vector::iterator i; for (i = roster.begin(); i != roster.end(); ++i) output(*i); cout << endl << endl; // search for desired persons by last name, "---" terminates Person searchRecord; for (;;) { cout << "Enter last name to search for (--- to stop): "; cin >> searchRecord.lastName; if (strcmp(searchRecord.lastName, "---") == 0) break; cout << "Searching for a person named " << searchRecord.lastName << "..." << endl; i = lower_bound(roster.begin(), roster.end(), searchRecord, nameComp); if (strcmp((*i).lastName, searchRecord.lastName) == 0) { cout << "Found "; output(*i); cout << endl; } else cout << "Sorry, there's no record of a person named " << searchRecord.lastName << endl << endl; } return 0; }