Well, the C++ standard library comes with a number of sorting functions and there's one that takes a "binary predicate function". I'm not sure how you use with std::list, but say you were storing your objects in a std::vector, you could do:
Code:
#include <algorithm>
#include <iostream>
#include <vector>
class Row
{
public:
Row(int row)
:
m_row(row) {}
int get_row() const
{
return m_row;
}
private:
int m_row;
};
static void print_collection(const std::vector<Row>&);
bool less_wrt_row(const Row& lhs, const Row& rhs)
{
return lhs.get_row() < rhs.get_row();
}
int
main()
{
std::vector<Row> collection;
collection.push_back(Row(39));
collection.push_back(Row(3));
collection.push_back(Row(202));
collection.push_back(Row(1));
std::cout << "Before sorting:" << std::endl;
print_collection(collection);
std::sort(collection.begin(), collection.end(), less_wrt_row);
std::cout << "After sorting:" << std::endl;
print_collection(collection);
return 0;
}
static void
print_collection(const std::vector<Row>& collection)
{
std::vector<Row>::const_iterator itr = collection.begin();
while(itr != collection.end())
{
std::cout << itr->get_row() << std::endl;
++itr;
}
}
Output:
Code:
$ ./foo.exe
Before sorting:
39
3
202
1
After sorting:
1
3
39
202
Using a binary predicate function is very nice if you have a class that should be sorted on different criteria at different times, simply select the proper predicate. If you *always* sort on row, you could define operator< for your class, and call the std::sort that does not take a predicate. There is also a stable_sort available to you should you need it.
Hope that helps