开发者

Finding max_element of a vector where a member is used to decide if its the maximum

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?


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; });


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;
}


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/


Implement operator< in your class, the call:

maxSoFar =  *(std::max_element(as.begin(), as.end()));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜