std::min_element
出自cppreference.com
|
|
該頁由英文版wiki使用Google Translate機器翻譯而來。
該翻譯可能存在錯誤或用詞不當。滑鼠停留在文本上可以看到原版本。你可以幫助我們修正錯誤或改進翻譯。參見說明請點擊這裡. |
| 在頭文件 <algorithm> 中定義
|
||
| template< class ForwardIt > ForwardIt min_element( ForwardIt first, ForwardIt last ); |
(1) | |
| template< class ForwardIt, class Compare > ForwardIt min_element( ForwardIt first, ForwardIt last, Compare comp ); |
(2) | |
查找的範圍內
[first, last)中最小的元素。使用operator<的值進行比較的第一個版本,第二個版本使用給定的比較函數comp.原文:
Finds the smallest element in the range
[first, last). The first version uses operator< to compare the values, the second version uses the given comparison function comp.目錄 |
[編輯] 參數
| first, last | - | 前向迭代器定義的範圍檢查
原文: forward iterators defining the range to examine |
| cmp | - | 比較函數,如果 if *a is less than *b,返回true。該函數的簽名形式如下: bool cmp(const Type1 &a, const Type2 &b); 雖然函數簽名中const &不是必須的,但是函數必須保證不會修改傳遞給它的對象。 |
| 類型要求 | ||
-ForwardIt 必須滿足 ForwardIterator 的要求。
| ||
[編輯] 返回值
迭代器的範圍內
[first, last)最小的元素。如果幾個元素的取值範圍為最小的元素是等價的,返回的迭代器的第一個這樣的元件。返回last的範圍內是空原文:
Iterator to the smallest element in the range
[first, last). If several elements in the range are equivalent to the smallest element, returns the iterator to the first such element. Returns last if the range is empty.[編輯] 複雜度
究竟max(N-1,0)比較,N = std::distance(first, last).
原文:
Exactly max(N-1,0) comparisons, where N = std::distance(first, last).
[編輯] 可能的實現
| 版本一 |
|---|
template<class ForwardIt> ForwardIt min_element(ForwardIt first, ForwardIt last) { if (first == last) return last; ForwardIt smallest = first; ++first; for (; first != last; ++first) { if (*first < *smallest) { smallest = first; } } return smallest; } |
| 版本二 |
template<class ForwardIt, class Compare> ForwardIt min_element(ForwardIt first, ForwardIt last, Compare comp) { if (first == last) return last; ForwardIt smallest = first; ++first; for (; first != last; ++first) { if (comp(*first, *smallest)) { smallest = first; } } return smallest; } |
[編輯] 示例
#include <algorithm> #include <iostream> #include <vector> int main() { std::vector<int> v{3, 1, 4, 1, 5, 9}; std::vector<int>::iterator result = std::min_element(v.begin(), v.end()); std::cout << "min element at: " << std::distance(v.begin(), result); }
輸出:
min element at: 1
[編輯] 另請參閱
| 返回區間內的最大元素 (函數模板) | |
| (C++11) |
返回區間內的最小元素和最大元素 (函數模板) |
| 返回兩個元素中的較小者 (函數模板) |