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
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Row {
std::string name;
std::string sign;
int age;
struct ColumnSorter {
int column;
ColumnSorter(int column)
: column(column)
{ }
/// > (greater than) for descending order
/// < (less than) for ascending order
/// use templates, if-statements, or virtual methods to customize further
bool operator() (const Row& row1, const Row& row2)
{
if (column == 0)
{
return (row1.name > row2.name);
}
else if (column == 1)
{
return (row1.sign > row2.sign);
}
else if (column == 2)
{
return (row1.age > row2.age);
}
else
{
return false;
}
}
};
};
std::ostream& operator<<(std::ostream& os, const std::vector<Row>& rows)
{
for (size_t i = 0; i < rows.size(); i++)
{
os << rows[i].name << " " << rows[i].sign << " " << rows[i].age << '\n';
}
return os;
}
template <typename Collection, typename SortingPredicate>
void sort(Collection& collection, const SortingPredicate& method)
{
std::sort(collection.begin(), collection.end(), method);
}
int main()
{
std::vector<Row> rows {
{ "Billy", "Cancer", 22 },
{ "Morgan", "Gemini", 11 },
{ "Wyatt", "Aries", 44 }
};
std::cout << rows << '\n';
sort(rows, Row::ColumnSorter(0));
std::cout << rows << '\n';
sort(rows, Row::ColumnSorter(1));
std::cout << rows << '\n';
sort(rows, Row::ColumnSorter(2));
std::cout << rows << '\n';
}
|