Ask and you shall receive. Here you go.
Case 1: Specialized function object - functor.
struct functor
{
bool operator() (const numberedString& a,
const numberedString& b)
{
if ((a.n != 0) && (b.n != 0))
{
return a.n < b.n;
}
return a.s < b.s;
}
};
Case 2: Overloading operator < in structure.
struct numberedString
{
string s;
int n;
bool operator<(const numberedString& other) const
{
if ((n != 0) && (other.n != 0))
{
return n < other.n;
}
return s < other.s;
}
};
Usage:
Overloading the operator<
allows functions to compare instances of your structure naturally:
numberedString c, d;
if (c < d)
{
cout << "c < d\n";
}
else
{
cout << "c >= d\n";
}
The functor allows you to pass a comparison algorithm to ordering functions like std::sort
:
numberedString array[25];
std::sort(&array[0], &array[25], functor);
Note: See std::sort for exact syntax.
BTW, what are the rules for when one variable has a number of zero and the other doesn't?