Это зависит от того, как вы определяете «элегантный», но да, это можно сделать. На самом деле, разными способами.
В Стандартном C ++ вы можете использовать Функтор:
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class Gizmo
{
public:
int n_;
};
class BiggestGizmo : public std::binary_function<bool, Gizmo, Gizmo>
{
public:
bool operator()(const Gizmo& lhs, const Gizmo& rhs) const
{
return lhs.n_ > rhs.n_;
}
};
int main()
{
typedef vector<Gizmo> Gizmos;
Gizmos gizmos;
Gizmos::const_iterator it = max_element(gizmos.begin(), gizmos.end(), BiggestGizmo());
}
В C ++ 0X вы можете использовать лямбду:
#include <algorithm>
#include <vector>
using namespace std;
class Gizmo
{
public:
int n_;
};
int main()
{
typedef vector<Gizmo> Gizmos;
Gizmos gizmos;
Gizmos::const_iterator it = max_element(gizmos.begin(), gizmos.end(), [](const Gizmo& lhs, const Gizmo& rhs) -> bool
{
return lhs.n_ > rhs.n_;
});
}