代码之家  ›  专栏  ›  技术社区  ›  math

求向量的max元素,其中一个成员用于确定其最大值

  •  6
  • math  · 技术社区  · 15 年前

    考虑一个类A,它有一个成员x和一个STD::vector & lt;现在搜索向量中所有元素的最大x是一项常见的任务。显然,如果X上有迭代器,我只能使用STD::Max元素,但我必须自己编写一个,或者只做一个简单的for循环。

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

    但是太无聊了,我太懒了。有更好的选择吗?

    4 回复  |  直到 15 年前
        1
  •  6
  •   Naveen    15 年前

    boost 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
  •  24
  •   Benjamin Lindley    15 年前

    std::max_element(as.begin(), as.end(),
        [](A a, A b){ return a.x < b.x; });
    
        3
  •  1
  •   BЈовић    15 年前
        4
  •  0
  •   Nim    15 年前

    operator<

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