Originally Posted by
Elysia
You can define how comparisons of different S objects is done via operator overloading. Example:
Code:
struct S
{
std::string myWord;
int a;
int b;
friend auto operator < (const S& left, const S& right) -> bool { return left.a < right.b; }
};
(If you don't have a C++11 compiler, you should declare the operator as
friend bool operator < (const S& left, const S& right))
That's all. max_element will use operator < to determine which object S is smaller than the other, so if you define that operator for S, everything works beautifully without using a comparator function.
Many thanks, it is good to know that operator overloading would also work. Of course, I am beginning to use C++11 also, and g++ seems to work well with Ubuntu Linux. But in the code that you wrote, it seems to me that in the line
Code:
friendauto operator < (constS& left, constS& right) -> bool{ return left.a < right.b; }
you intended to write:
Code:
friendauto operator < (constS& left, constS& right) -> bool{ return left.a < right.a; }
so that the "<" focuses only on the 'a' components of S, without involving b yet.
However, what if we also want to compare the 'b' components on other occasions?
Perhaps we can put two friend functions inside the struct, one for 'a' and one for 'b', like this:
Code:
struct S
{
std::string myWord;
int a;
int b;
friend auto operator < (const S& left, const S& right) -> bool { return left.a < right.a; }
friend auto operator < (const S& left, const S& right) -> bool { return left.b < right.b; }
};
But in this case, how will the compiler know which version of "<" we intended to use when we apply the std::max_element() function, was it for the the component 'a' or 'b'? How would you then write the entire code?