為了計算給定列表中所有元素中的最小元素,我們有std::min,但是如果我們想在列表的sub-section中而不是整個列表中找到最小元素,該怎麽辦。為此,我們在C++中提供了std::min_element。
std::min_element在頭文件<algorithm>中定義,它返回一個迭代器,該迭代器指向在[first,last)範圍內具有最小值的元素。
與可以以三種方式使用的std::min不同,std::min_element可以以兩種方式使用。可以使用運算符<(第一個版本)或使用預定義的函數(第二個版本)來執行比較。如果一個以上的元素滿足最小條件,則迭代器將返回指向此類元素中第一個的元素。這兩個版本定義如下:
- 使用“ <”比較元素:
用法:template ForwardIterator min_element (ForwardIterator first, ForwardIterator last); first:Forward iterator pointing to the beginning of the range. last:Forward iterator pointing to the end of the range. 返回值: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty.
// C++ program to demonstrate the use of std::min_element #include <iostream> #include <algorithm> using namespace std; int main() { int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // fifth element int* i1; i1 = std::min_element(v + 2, v + 5); cout << *i1 << "\n"; return 0; }
輸出:
2
- 對於基於預定義函數的比較:
用法:
template ForwardIterator min_element (ForwardIterator first, ForwardIterator last, Compare comp); Here, first and last are the same as previous case. comp: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered less than the second. The function shall not modify any of its arguments. This can either be a function pointer or a function object. 返回值: It return a pointer to the smallest element in the range, and in case if there are more than one such element, then it points to the first one. It points to the last in case the range is empty.
// C++ program to demonstrate the use of std::min_element #include <iostream> #include <algorithm> using namespace std; // Defining the BinaryFunction bool comp(int a, int b) { return (a < b); } int main() { int v[] = { 9, 4, 7, 2, 5, 10, 11, 12, 1, 3, 6 }; // Finding the minimum value between the third and the // ninth element int* i1; i1 = std::min_element(v + 2, v + 9, comp); cout << *i1 << "\n"; return 0; }
輸出:
1
相關文章:
相關用法
注:本文由純淨天空篩選整理自 std::min_element in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。