/* list_test.cpp * * This simple test app shows the way I finally found of getting a * std::list to be sortable based on a member within the class being * inserted into the list. There may well be a better way, but this * does at least work. * * Compile using * * gcc -Wall -O2 -o list_test list_test.cpp * * Run using * * ./list_attr * * It's very simple, but maybe it'll help others out as I spent a bit of * time bashing the wall of bricks on this one. */ #include #include class number { public: number(); number(int number); number(const number &); bool operator < (const number &) const; void PrintToStream(void); private: int num; }; number::number() { num = 0; } number::number(int n) { num = n; } number::number(const number &n) { num = n.num; } void number::PrintToStream(void) { printf(" %4d\n", num); } bool number::operator < (const number &n) const { return (n.num > num); } struct ltnumber { bool operator()(const number * n1, const number *n2) const { return (*n1 < *n2); } }; int main(int argc, char *argv[]) { std::listnums; std::list::iterator it; int i; for (i = 10; i > 0; i--) { number *n = new number(i); nums.push_back(n); } printf("Initialised to:\n"); for (it = nums.begin(); it != nums.end(); it++) (*it)->PrintToStream(); nums.sort( ltnumber() ); printf("After sort:\n"); for (it = nums.begin(); it != nums.end(); it++) (*it)->PrintToStream(); return 0; }