C++中的max_element()与min_element()

来源:互联网 发布:知乎live 编辑:程序博客网 时间:2024/06/04 23:32

max_element()与min_element()都定义于头文件 <algorithm>,分别实现了返回区间 [first,last)中第一个最大值和第一个最小值对应的迭代器。


Example

// min_element/max_element example#include <iostream>     // std::cout#include <algorithm>    // std::min_element, std::max_elementbool 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;}
output:

The smallest element is 2The largest element is 9The smallest element is 2The largest element is 9The smallest element is 2The largest element is 9

原创粉丝点击