Source of set18.cpp


  1: //set18.cpp

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

  8: /**
  9: A class for storing names of Canadian provinces and their capitals.
 10: */
 11: class Province
 12: {
 13: public:
 14:     Province()                   { name = capital = ""; }
 15:     Province(string n)           { name = n; capital = ""; }
 16:     Province(string n, string c) { name = n; capital = c; }
 17:     string getName()             { return name;    }
 18:     string getCapital()          { return capital; }
 19: private:
 20:     string name;
 21:     string capital;
 22: };

 24: bool operator<
 25: (
 26:     Province p1,
 27:     Province p2
 28: )
 29: {
 30:     return p1.getName() < p2.getName();
 31: }

 33: ostream &operator<<
 34: (
 35:     ostream &os,
 36:     Province &prov
 37: )
 38: {
 39:     os << prov.getName() << "'s capital is ";
 40:     os << prov.getCapital() << "." << endl;
 41:     return os;
 42: } 

 44: int main()
 45: {
 46:     cout << "\nThis program first creates a set of provinces and their "
 47:         "capitals and displays\nthis information. Then it allows the user "
 48:         "to enter the name of a province and\nif the province is found in "
 49:         "the set, its capital is displayed.";
 50:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 52:     //Initialize the set
 53:     set<Province> provinces;
 54:     provinces.insert(Province("Newfoundland", "Saint John's"));
 55:     provinces.insert(Province("Prince Edward Island", "Charlottetown"));
 56:     provinces.insert(Province("Nova Scotia", "Halifax"));
 57:     provinces.insert(Province("New Brunswick", "Fredericton"));
 58:     provinces.insert(Province("Ontario", "Toronto"));
 59:     provinces.insert(Province("Manitoba", "Winnipeg"));
 60:     provinces.insert(Province("Saskatchewan", "Regina"));
 61:     provinces.insert(Province("Alberta", "Edmonton"));
 62:     provinces.insert(Province("British Columbia", "Victoria"));
 63:     
 64:     //Display contents of the set of provinces
 65:     set<Province>::iterator p = provinces.begin();
 66:     cout << endl;
 67:     while(p != provinces.end()) cout << *p++;
 68:     
 69:     cout << "\nEnter the name of a province to see its capital: ";
 70:     string nameOfProvince;
 71:     getline(cin, nameOfProvince);
 72:     p = provinces.find(Province(nameOfProvince));
 73:     if (p != provinces.end())
 74:         cout << nameOfProvince << " found.\n" << *p;
 75:     else 
 76:         cout << "That province is not in the given set of provinces.\n";
 77:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 78: }