You have two options for using std::sort
. One is to overload operator <
for your class:
bool operator< (const Card &lhs, const Card &rhs) {
return lhs.value < rhs.value;
}
However, only do this if it really makes sense to always compare Card
objects like this. If you only need this for a particular sorting, you can use the version of sort
which accepts a custom comparator.
There are multiple ways to define the predicate. For reusable, but simple criteria, a static function in the class can be used:
class Card
{
public:
// ... as before
static bool lesserValue(const Card &lhs, const Card &rhs) {
return lhs.value < rhs.value;
}
};
Usage:
std::sort(from, to, &Card::lesserValue);
For a one-shot thing (or for complex criteria which need to preserve internal state), use a class derived from std::binary_function
and implement the comaprison logic in its operator()
. In C++11, you can also use lambda functions for this:
std::sort(from, to, [](const Card &lhs, const Card &rhs) { return lhs.value < rhs.value; });