查找向量的max_element,其中成员用于确定其最大值 [英] Finding max_element of a vector where a member is used to decide if its the maximum

查看:59
本文介绍了查找向量的max_element,其中成员用于确定其最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑具有成员x和std :: vector的类A.A>.现在,在向量内的所有元素中搜索最大x是一项常见的任务.显然,如果x上存在迭代器,则只能使用std :: max_element.但是我必须自己编写一个,否则我只做一个简单的for循环.

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?

推荐答案

如果可以使用 boost ,则可以为 max_element 期望的二进制谓词编写一个lambda表达式.:

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

这篇关于查找向量的max_element,其中成员用于确定其最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆