Sunday 3 June 2018

Chapter 9 // Exercise 3 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


Chapter 9 // Exercise 3



Replace Name_pair::print() with a (global) operator <<  and define  ==  and !=  for Name_pairs.

#include "stdafx.h"
#include "std_lib_facilities.h"

class Name_pairs
{
private:
 vector<string> name;
 vector<double> age;
public:
 void read_names(int iterator);  //read in a series of names
 void read_ages();     //read in age for name
 void sortNP();      //sort the vectors alphabetically by name
 vector<string> getNames() { return name; }
 vector<double> getAges() { return age; }
};

ostream& operator<<(ostream& os, Name_pairs& n) //print the vectors
{
 cout << endl;
 for (int i = 0; i < n.getNames().size(); ++i)
  os << "Name: " << n.getNames()[i] << "     Age: " << n.getAges()[i] << endl;
 return os;
}
//equals
bool operator==(Name_pairs& a, Name_pairs& b)
{
 return a.getNames() == b.getNames() &&
  a.getAges() == b.getAges();
}

//not equals
bool operator!=(Name_pairs& a, Name_pairs& b)
{
 return !(a == b);
}
void Name_pairs::read_names(int iterator)
{
 string names;
 for (int i = 0; i < iterator; ++i)
 {
  cout << "Name: ";
  cin >> names;
  name.push_back(names);
  cout << endl;
 }
}

void Name_pairs::read_ages()
{
 double ages;
 for (int i = 0; i < name.size(); ++i)
 {
  cout << "Age for " << name[i] << ": ";
  cin >> ages;
  age.push_back(ages);
  cout << endl;
 }
}

void Name_pairs::sortNP()
{
 vector<string> name_copy = name;
 vector<double> age_copy = age;

 sort(name.begin(), name.end());  //sort actual names

 //go through each member of sorted name
 for (int i = 0; i < name.size(); ++i)
 {
  //go through each member of original copy name
  for (int j = 0; j < name.size(); ++j)
  {
   //if sorted name matches original
   if (name[i] == name_copy[j])
   {
    //assign original age to new position to match sorted vector
    age[i] = age_copy[j];
   }
  }
 }
}

int main()
{
 cout << "How many names to read in? > ";
 int howMany;
 cin >> howMany;

 Name_pairs namePair;

 //read in names
 namePair.read_names(howMany);

 //read in ages
 namePair.read_ages();

 //print
 cout << namePair;

 //sort namePair alphabetically
 namePair.sortNP();

 //print
 cout << namePair;

 keep_window_open();

 return 0;
}


The most challenging part of this was getting the ostream operator to work properly. At the moment he's only shown examples for having it outside of the class but I'm pretty sure there is a way to have it inside the class as a member.

Also, he didn't particularly specify what type of == and != he wanted. Was to compare the name_pair in general or to compare specific days? I did it generally, however it could be improved to compare specific days and ages.

No comments:

Post a Comment