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


發佈了97 篇原創文章 · 獲贊 47 · 訪問量 54萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章