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
|
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
struct RecordsType
{
std::string state;
int someValue;
};
struct SortRecordsAscending
{
bool operator()(const RecordsType& lhs, const RecordsType& rhs)
{
return (lhs.state < rhs.state);
// if null terminated array
//return (strcmp(lhs.str, rhs.str) < 0);
}
};
struct SortRecordsDescending
{
bool operator()(const RecordsType& lhs, const RecordsType& rhs)
{
return (rhs.state < lhs.state);
// if null terminated array
//return (strcmp(lhs.str, rhs.str) > 0);
}
};
void SortingObjectsExample()
{
const int SIZE(5);
RecordsType MyArray[5] =
{
{ "MA", 5}, { "PA", 1 }, { "GE", 3 }, { "SC", 4 }, { "MA", 2 }
};
// notice that the SortRecordsAsending is being constructed. The third arg
// is an instance of the SortRecordsAsending struct. Its operator()
// is invoked as sort tries to determine the order of the objects in the
// array.
std::sort(MyArray, MyArray + SIZE, SortRecordsAscending());
for(int i = 0; i < SIZE; ++i)
std::cout << MyArray[i].state << ' ';
std::cout << std::endl;
// shuffle
std::random_shuffle(MyArray, MyArray + SIZE);
for(int i = 0; i < SIZE; ++i)
std::cout << MyArray[i].state << ' ';
std::cout << std::endl;
// sort descending.
std::sort(MyArray, MyArray + SIZE, SortRecordsDescending());
for(int i = 0; i < SIZE; ++i)
std::cout << MyArray[i].state << ' ';
std::cout << std::endl;
}
int main()
{
const int SIZE(5);
int MyArray[SIZE] = { 5, 4, 1, 3, 2 };
std::sort(MyArray, MyArray + SIZE); // sorts ascending by default
for(int i = 0; i < SIZE; ++i)
std::cout << MyArray[i];
std::cout << std::endl;
SortingObjectsExample();
}
|