问题
Consider a class A having a member x and a std::vector< A >. Now its a common task to search for the maximal x among all elements inside the vector. Clearly I can only use std::max_element if there is an iterator on the x's. But I must write one by my own, or I just make a simple for loop.
maxSoFar = -std::numeric_limits< double >::max();
for( std::vector< A >::const_iterator cit = as.begin(); cit != as.end(); ++cit )
{
if( cit->x > maxSoFar )
maxSoFar = cit->x;
}
but it's so tedious, and I am so lazy.. Is there a better option?
回答1:
If you can use boost
then you can write a lambda expression for the binary predicate expected by max_element
:
struct A
{
A(int n): x(n)
{
}
int x;
};
using namespace std;
using namespace boost::lambda;
int main()
{
vector<A> as;
as.push_back(A(7));
as.push_back(A(5));
as.push_back(A(3));
vector<A>::iterator iter = max_element(as.begin(), as.end(), bind(&A::x, _2) > bind(&A::x, _1));
int max = iter->x;
}
回答2:
You can pass a comparator to max_element. And if your compiler supports lambdas(it probably does), this is easy:
std::max_element(as.begin(), as.end(),
[](A a, A b){ return a.x < b.x; });
回答3:
1) Change the 1st line to this :
maxSoFar = *(as.begin());
2) Implement a custom comparator, and use max_element (as you wanted) : http://www.cplusplus.com/reference/algorithm/max_element/
回答4:
Implement operator<
in your class, the call:
maxSoFar = *(std::max_element(as.begin(), as.end()));
来源:https://stackoverflow.com/questions/3994890/finding-max-element-of-a-vector-where-a-member-is-used-to-decide-if-its-the-maxi