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
|
#include <algorithm>
#include <iostream>
struct myobject
{
int a, b, c;
double d, e;
};
std::ostream &operator<<(std::ostream &os, const myobject &o)
{
os << o.a << ", " << o.b << ", " << o.c << ", " << o.d << ", " << o.e;
return os;
}
bool sort_by_a(const myobject &a, const myobject &b) { return a.a < b.a; }
bool sort_by_b(const myobject &a, const myobject &b) { return a.b < b.b; }
bool sort_by_c(const myobject &a, const myobject &b) { return a.c < b.c; }
bool sort_by_d(const myobject &a, const myobject &b) { return a.d < b.d; }
bool sort_by_e(const myobject &a, const myobject &b) { return a.e < b.e; }
template <typename T, size_t S> size_t ArraySize(const T (&)[S]) { return S; }
int main()
{
myobject o[] = {
{ 1, 14, 12, 7.0, 99.0 },
{ 41, 4, 27, 8.0, 3.0 },
{ 12, 18, 3, 1.0, 7.0 }
};
std::cout << "original order" << std::endl;
for (const myobject* p = o; p != o + ArraySize(o); ++p)
std::cout << *p << std::endl;
std::cout << std::endl;
std::cout << "sort by a" << std::endl;
std::sort(o, o + ArraySize(o), sort_by_a);
for (const myobject* p = o; p != o + ArraySize(o); ++p)
std::cout << *p << std::endl;
std::cout << std::endl;
std::cout << "sort by b" << std::endl;
std::sort(o, o + ArraySize(o), sort_by_b);
for (const myobject* p = o; p != o + ArraySize(o); ++p)
std::cout << *p << std::endl;
std::cout << std::endl;
//...
return 0;
}
|