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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
// chapter8ex7.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 13 / 2017
// Bjarne Stoustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 8 Exercise 7
// Exercise Specifications
/**
* Read five names into a vector<string> name , then prompt the user for
* the ages of the people named and store the ages in a vector<double> age .
* Then print out the five ( name[i] , age[i] ) pairs. Sort the names ( sort(name
* .begin(),name.end()) ) and print out the ( name[i] , age[i] ) pairs. The tricky
* part here is to get the age vector in the correct order to match the sorted
* name vector . Hint: Before sorting name , take a copy and use that to
* make a copy of age in the right order after sorting name . Then, do that
* exercise again but allowing an arbitrary number of names.
*/
#include "../../std_lib_facilities.h"
#include <iterator>
vector<string> get_names_input();
vector<double> get_ages_input();
vector<double> find_indexes(vector<string> &names, vector<double> &ages);
void parallel_sort(const vector<double> &indexes, vector<double> &ages);
void print_vectors(const vector<string> &names, const vector<double> &ages);
int main()
{
vector<string> names = get_names_input();
vector<double> ages = get_ages_input();
vector<double> indexes = find_indexes(names, ages);
parallel_sort(indexes, ages);
print_vectors(names, ages);
keep_window_open();
}
vector<string> get_names_input()
{
cout << "Please enter 5 names: ";
string name;
vector<string> names;
do
{
cin >> name;
cin.ignore();
names.push_back(name);
}
while (names.size() < 5);
return names;
}
vector<double> get_ages_input()
{
cout << "Please enter those people's ages: ";
double age;
vector<double> ages;
do
{
cin >> age;
cin.ignore();
ages.push_back(age);
}
while (ages.size() < 5);
return ages;
}
vector<double> find_indexes(vector<string> &names, vector<double> &ages)
{
vector<string> names_copy = names;
vector<double> age_index;
sort(names.begin(), names.end());
for (auto iter = names_copy.cbegin(); iter != names_copy.cend(); ++iter)
{
auto c_iter = find(names.cbegin(), names.cend(), *iter);
if (c_iter != names.end())
{
age_index.push_back(distance(names.cbegin(), c_iter));
}
}
return age_index;
}
void print_vectors(const vector<string> &names, const vector<double> &ages)
{
for (unsigned i = 0; i < names.size(); ++i)
{
cout << names[i] << ", " << ages[i] << '\n';
}
}
void parallel_sort(const vector<double> &indexes, vector<double> &ages)
{
for (unsigned i = 0; i < indexes.size(); ++i)
{
//TODO
}
}
|