转载

C++笔记——std::min_element和std::max_element

https://blog.csdn.net/breeze5428/article/details/25918925

参考网页:

http://en.cppreference.com/w/cpp/algorithm/min_element



主要有两种用法

template< class ForwardIt > 
ForwardIt min_element( ForwardIt first, ForwardIt last );

template< class ForwardIt, class Compare >
ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp );
。其中第一种采用默认的比较函数<,第二种自定义比较函数。first和last是被比较的元素的地址或迭代器范围 [ first,last)。以下是一个具体的实例。
// min_element/max_element example
#include <iostream>     // std::cout
#include <algorithm>    // std::min_element, std::max_element
 
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:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7) << '\n';
 
  // using function myfn as comp:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myfn) << '\n';
 
  // using object myobj as comp:
  std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
  std::cout << "The largest element is "  << *std::max_element(myints,myints+7,myobj) << '\n';
 
  return 0;
}


文章最后发布于: 2018-07-14 01:23:19
展开阅读全文
0 个人打赏

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览