首页 > 代码库 > min_element()与max_element()

min_element()与max_element()

所在头文件:#include<algorithm>

头文件分类:Min/Max

函数功能:min_element()返回一个迭代器指针,指向一个范围内[first,last)的最小元素;max_element()返回一个迭代器指针,指向一个范围内[first,last)的最小元素。如果不止一个元素满足这个条件,返回的迭代器指向第一个这样的元素。

min_element()函数模板的功能相当于:

template <class ForwardIterator>
  ForwardIterator min_element ( ForwardIterator first, ForwardIterator last )
{
  if (first==last) return last;
  ForwardIterator smallest = first;

  while (++first!=last)
    if (*first<*smallest)    // or: if (comp(*first,*smallest)) for version (2)
      smallest=first;
  return smallest;
}

max_element()函数模板的功能相当于:

template <class ForwardIterator>
  ForwardIterator max_element ( ForwardIterator first, ForwardIterator last )
{
  if (first==last) return last;
  ForwardIterator largest = first;

  while (++first!=last)
    if (*largest<*first)    // or: if (comp(*largest,*first)) for version (2)
      largest=first;
  return largest;
}

函数模板:

/**
**author :Or_me **
╭︿︿︿╮
{/ A  C /} 
 ( (OO) ) 
  ︶︶︶ 
**    **
**min_element/max_element example**
** 2014 年 7月 2日**
**/
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <cstdio>
#include <string>
#include <cctype>
#include <climits>
#include <cstring>
#include <cstdlib>
#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 () 
{
  system("color 5b");
  int myints[] = {3,7,2,5,6,4,9};

  cout<<"using default comparison:"<<endl;
  cout<<"The smallest element is "<<*min_element(myints,myints+7)<<endl;
  cout<<"The largest element is " <<*max_element(myints,myints+7)<<endl<<endl;

  cout<<"using function myfn as comp:"<<endl;
  cout<<"The smallest element is "<<*min_element(myints,myints+7,myfn)<<endl;
  cout<<"The largest element is " <<*max_element(myints,myints+7,myfn)<<endl<<endl;

  cout<<"using object myobj as comp:"<<endl;
  cout<<"The smallest element is "<<*min_element(myints,myints+7,myobj)<<endl;
  cout<<"The largest element is " <<*max_element(myints,myints+7,myobj)<<endl<<endl;
  return 0;
}



min_element()与max_element()