zoukankan      html  css  js  c++  java
  • c++ max_elment和min_element

      max_element和min_element用来求一个范围内的最大值和最小值

    template <class ForwardIterator>
      ForwardIterator max_element ( ForwardIterator first, ForwardIterator last );
    
    template <class ForwardIterator, class Compare>
      ForwardIterator max_element ( ForwardIterator first, ForwardIterator last,
                                    Compare comp );

    int max= *max_element(v.begin(),v.end());  //注意返回的是一个迭代器,*取
      int max= *min_element(energy.begin(),energy.end());  //求最小值
    // min_element/max_element
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    bool myfn(int i, int j) { return i<j; }
    
    struct myclass {
      bool operator() (int i,int j) { return i<j; }
    } myobj;
    
    int main () {
      int myints[] = {3,7,2,5,6,4,9};
    
      // using default comparison:
      cout << "The smallest element is " << *min_element(myints,myints+7) << endl;
      cout << "The largest element is " << *max_element(myints,myints+7) << endl;
    
      // using function myfn as comp:
      cout << "The smallest element is " << *min_element(myints,myints+7,myfn) << endl;
      cout << "The largest element is " << *max_element(myints,myints+7,myfn) << endl;
    
      // using object myobj as comp:
      cout << "The smallest element is " << *min_element(myints,myints+7,myobj) << endl;
      cout << "The largest element is " << *max_element(myints,myints+7,myobj) << endl;
    
      return 0;
    }

    The example illustrates how the comparison object can be either a function or an object whose class defines theoperator() member. In this case both have been defined to perform a standard less-than comparison.
    Output:

    The smallest element is 2
    The largest element is 9
  • 相关阅读:
    POJ 1873 计算几何
    POJ 1584 计算几何
    POJ 1410 计算几何
    BZOJ 1208 set
    BZOJ 1503 splay
    BZOJ 5277 IQ题orz
    Codeforces Round #549 (Div. 2)A. The Doors
    (原创)同余定理
    April Fools Day Contest 2019 A. Thanos Sort
    PTA数据结构之 List Leaves
  • 原文地址:https://www.cnblogs.com/youxin/p/2566570.html
Copyright © 2011-2022 走看看