std::max在頭文件<algorithm>中定義,用於查找傳遞給它的最大數字。如果有多個,則返回第一個。可以按以下方式使用它:
- 它比較在其參數中傳遞的兩個數字,並返回兩個中較大的一個,如果兩個相等,則返回第一個。
- 它還可以使用二進製函數比較兩個數字,該二進製函數由用戶預定義,然後作為參數傳遞給std::max(。
- 如果我們想在給定列表中找到最大的元素,它也很有用;如果列表中存在多個元素,它會返回第一個元素。
這三個版本定義如下:
- 使用“
用法:
template
constexpr const T& max (const T& a, const T& b); Here, a and b are the numbers to be compared. 返回: Larger of the two values.CPP
// C++ program to demonstrate the use of std::max // C++ program to demonstrate the use of std::max #include<iostream> #include<algorithm> using namespace std; int main() { // Comparing ASCII values of a and b cout << std::max('a','b') << "\n"; // Returns the first one if both the numbers // are same cout << std::max(7,7); return 0; }
Python3
# Python 3 program to # demonstrate the use of std::max # Comparing ASCII # values of a and b print(max('a','b')) # Returns the first # one if both the numbers # are same print(max(7, 7)) # This code is contributed by # Smitha Dinesh Semwal
輸出:b 7
- 使用預定義函數比較元素:
用法:
template
constexpr const T& max (const T& a, const T& b, Compare comp); Here, a and b are the numbers to be compared. comp: Binary function that accepts two values of type T as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as f irst 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. 返回: Larger of the two values.// C++ program to demonstrate the use of std::max #include<iostream> #include<algorithm> using namespace std; // Defining the binary function bool comp(int a, int b) { return (a < b); } int main() { int a = 7; int b = 28; cout << std::max(a,b,comp) << "\n"; // Returns the first one if both the numbers // are same cout << std::max(7,7,comp); return 0; }
輸出:
28 7
- 在列表中查找最大元素:
用法:
template
constexpr T max (initializer_list Here, comp is optional and can be skipped. il: An initializer_list object. 返回: Largest of all the values.il, Compare comp); // C++ program to demonstrate the use of std::max #include<iostream> #include<algorithm> using namespace std; // Defining the binary function bool comp(int a, int b) { return (a < b); } int main() { // Finding the largest of all the numbers cout << std::max({1, 2, 3, 4, 5, 10, -1, 7},comp) << "\n"; return 0; }
輸出:
10
相關文章:
相關用法
注:本文由純淨天空篩選整理自 std::max in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。