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
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Family
{
std::string familyName;
int familyAge;
Family(string name, int age) : familyName(name), familyAge(age) {}
};
// sorting
bool sortByAge(const Family &val1, const Family &val2) { return val1.familyAge < val2.familyAge; }
bool sortByName(const Family &val1, const Family &val2) { return val1.familyName < val2.familyName; }
int main()
{
// create a vector of type Family for family members.
std::vector<Family> familyList;
// you could loop through each file in turn and enter their details in the vector
// I am just going to enter some dummy data as an example just to show you whats
// needed. Below I am passing Name and age (defined in Family structure), if
// you are just storing names then age can be removed.
familyList.push_back(Family("Joe Bloggs", 43));
familyList.push_back(Family("Paul Jones", 21));
familyList.push_back(Family("Deborah Sanders", 31));
familyList.push_back(Family("Dylan Wood", 12));
// display them
cout << "Before any sorting..." << endl << endl;
for (int i = 0; i < 4; i++)
cout << familyList[i].familyName << ", aged " << familyList[i].familyAge << "." << endl;
// so all your data has been read into the vector from all three files,
// lets sort it... first we will sort by age.
sort(familyList.begin(), familyList.end(), sortByAge);
// display them
cout << endl << "After sorting by age..." << endl << endl;
for (int i = 0; i < 4; i++)
cout << familyList[i].familyName << ", aged " << familyList[i].familyAge << "." << endl;
// sort by name.
sort(familyList.begin(), familyList.end(), sortByName);
// display them
cout << endl << "After sorting by name..." << endl << endl;
for (int i = 0; i < 4; i++)
cout << familyList[i].familyName << ", aged " << familyList[i].familyAge << "." << endl;
return 0;
}
|