Source of set06.cpp


  1: //set06.cpp

  3: #include <iostream>
  4: #include <string>
  5: #include <set>
  6: using namespace std;

  8: class Person
  9: {
 10: public:
 11:     Person
 12:     (
 13:         string name, //in
 14:         int age      //in
 15:     )
 16:     {
 17:         this->name = name;
 18:         this->age = age;
 19:     }
 20:     string getName() { return name; }
 21:     int getAge()     { return age; }
 22:     bool operator<
 23:     (
 24:         const Person& other //in
 25:     ) const
 26:     {
 27:         return name < other.name;
 28:     }

 30: private:
 31:     string name;
 32:     int age;
 33: };



 37: int main()
 38: {
 39:     cout << "\nThis program illustrates a set of class objects.";
 40:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 42:     cout << "\nWe first define an array of Person objects, then we create "
 43:         "\na set of the same objects from the array.";
 44:     //Create an array of Person
 45:     Person a[] =
 46:     {
 47:         Person("William", 23),
 48:         Person("John", 20),
 49:         Person("Alice", 18),
 50:         Person("Peter", 24),
 51:         Person("Bob", 17)
 52:     };
 53:     set<Person> s(a, a+5);
 54:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');


 57:     cout << "\nHere is the information in the set of Person objects:\n";
 58:     set<Person>::iterator p = s.begin();
 59:     while (p != s.end())
 60:     {
 61:         cout << p->getName() << " is " << p->getAge() << " years old.\n";
 62:         ++p;
 63:     }
 64:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 65: }