function template
<algorithm>

std::min_element

默认 (1)
template <class ForwardIterator>  ForwardIterator min_element (ForwardIterator first, ForwardIterator last);
自定义 (2)
template <class ForwardIterator, class Compare>  ForwardIterator min_element (ForwardIterator first, ForwardIterator last,                               Compare comp);
Return smallest element in range
Returns an iterator pointing to the element with the smallest value in the range [first,last).

The comparisons are performed using either operator< for the first version, or comp for the second; An element is the smallest if no other element compares less than it. If more than one element fulfills this condition, the iterator returned points to the first of such elements.

此函数模板的行为等同于
1
2
3
4
5
6
7
8
9
10
11
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;
}

参数

first, last
Input iterators to the initial and final positions of the sequence to compare. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
comp
二元函数,接受范围中的两个元素作为参数,并返回一个可转换为 bool 的值。返回的值指示第一个参数传递的元素是否被视为小于第二个参数。
该函数不得修改其任何参数。
This can either be a function pointer or a function object.

返回值

An iterator to smallest value in the range, or last if the range is empty.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 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;
}

输出
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9


复杂度

Linear in one less than the number of elements compared.

数据竞争

访问范围 [first,last) 中的对象。

异常

如果任何比较操作抛出异常,则该函数抛出异常。
请注意,无效参数会导致未定义行为

另见