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
|
#include "Person.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void selectionSort ( vector<Person*> vec, bool (*compare) (int, int));
void swap ( Person &persPtr1 , Person &persPtr2);
bool ascending (int a, int b);
bool descending (int a, int b);
int main()
{
string name;
int age;
vector<Person*> people;
string order;
while (name != "q")
{
cout << "Enter name, q to quit: ";
getline(cin, name);
if (name != "q")
{
cout << "Enter age: ";
cin >> age;
Person* p = new Person(name,age);
cin.ignore();
people.push_back(p);
}
}
cout << "Enter the order to sort the people: ";
cin >> order;
if (order == "ascending") //Ascending
{
selectionSort(people, ascending);
cout << "Ascending order: " << endl;
for (int i = 0; i < people.size(); i++)
{
cout << people.at(i);
}
}
else if (order == "descending") //Ascending
{
selectionSort(people, descending);
cout << "Descending order: " << endl;
}
system("PAUSE");
return 0;
}
void selectionSort (vector<Person*> vec, bool (*compare) (int, int))
{
int num;
for (int i = 0; i < vec.size(); i++)
{
num = i;
for (int j = i+1; j < vec.size(); j++)
{
if (!(*compare) (vec.at(num)->getAge(), vec.at(j)->getAge()))
{
num = j;
}
}
swap (vec.at(num), vec.at(i));
}
}
void swap (Person& persPtr1 , Person& persPtr2)
{
Person temp = persPtr1;
persPtr1 = persPtr2;
persPtr2 = temp;
}
bool ascending (int a, int b)
{
return a < b;
}
bool descending (int a, int b)
{
return a > b;
}
|