Exercise solution chapter 9 from Programming -- Principles and Practice Using C++

Hello, I'm new with C++ and I'm learning with the book "Programming -- Principles and Practice Using C++ (Stroustrup)" (2009). Until now I'm doing all the final chapter's exercises but I stopped in 9.2 and I can't move on. I really need some help!

"Design and implement a 'Name_pairs' class holding (name,age) pairs where name is a 'string' and age is a 'double'. Represent that as a 'vector<string>' (called 'name') and a 'vector<double>' (called 'age') member. Provide an input operation 'red_names()' that reads a series of names. Provide a 'read_ages()' operation that prompts the user for an age for each name. Provide a 'print()' operation that prints out the ('name[i], age[i]') pairs (one per line) in the order determined by the 'name' vector. Provide a 'sort()' operation that sorts the 'name' vector in alphabetical order and reorganizes the 'age' vector to match. Implement all operations as member functions."

My big problem is also to connect the main function with all of this.

Thanks!
Here's the class tutorial of this site, maybe reading it will help a bit:
http://www.cplusplus.com/doc/tutorial/classes/

So we must code a Name_pairs class, that contains:
1) vector<string> member data.
2) vector<double> member data.
3) read_names() member function.
4) read_ages() member function.
5) print() member function.
6) sort() member function.

Observations relating to style:
a) using namespace std; is a bad habit* so we won't use it.
b) rule of thumb: member data is private, member functions are public.
c) member functions that don't change member data will be marked as const.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream> // std::cin, std::cout
#include <string> // std::string
#include <vector> // std::vector

class Name_pairs
{
private:

    std::vector<std::string> names;
    std::vector<double> ages;

public:

    void read_names()
    {
    }

    void read_ages()
    {
    }

    void print() const
    {
    }

    void sort()
    {
    }
};

int main()
{
    Name_pairs np;

    np.read_names();
    np.read_ages();
    np.sort();
    np.print();
}


Try to continue on your own from here. Here are some hints:
1) before reading the names, ask how many there are.
2) to read a name, use std::getline()**.
3) choose and implement a sorting algorithm***.

* http://www.parashift.com/c++-faq/using-namespace-std.html
** http://www.cplusplus.com/reference/string/string/getline/
*** http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/
Last edited on
Thanks, helped me a lot!
Topic archived. No new replies allowed.