std::min在头文件中定义,用于找出传递给它的最小数目。如果有多个,则返回第一个。
它可以通过以下三种方式使用:
- 它比较在其参数中传递的两个数字,并返回两个中较小的一个,如果两个相等,则返回第一个。
- 它还可以使用由用户定义的二进制函数比较两个数字,然后将其作为参数传递给std::min(。
- 如果我们想在给定列表中找到最小的元素,它也很有用;如果列表中存在多个元素,它会返回第一个元素。
这三个版本定义如下:
- 用于使用<:比较元素
用法:
template constexpr const T& min (const T& a, const T& b); a and b are the numbers to be compared. 返回: Smaller of the two values.
// C++ program to demonstrate the use of std::min #include <iostream> #include <algorithm> using namespace std; int main() { int a = 5; int b = 7; cout << std::min(a, b) << "\n"; // Returns the first one if both the numbers // are same cout << std::min(7, 7); return 0; }
输出:
5 7
- 使用预定义函数比较元素:
用法:
template constexpr const T& min (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 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. 返回: Smaller of the two values.
// C++ program to demonstrate the use of std::min #include <iostream> #include <algorithm> using namespace std; // Defining the binary function bool comp(int a, int b) { return (a < b); } int main() { int a = 5; int b = 7; cout << std::min(a, b, comp) << "\n"; // Returns the first one if both the numbers // are same cout << std::min(7, 7, comp); return 0; }
输出:
5 7
- 在列表中查找最小元素:
用法:template constexpr T min (initializer_list il, Compare comp); comp is optional and can be skipped. il: An initializer_list object. 返回: Smallest of all the values.
// C++ program to demonstrate the use of std::min #include <iostream> #include <algorithm> #include <vector> using namespace std; // Defining the binary function bool comp(int a, int b) { return (a < b); } int main() { // Finding the smallest of all the numbers cout << std::min({ 1, 2, 3, 4, 5, 0, -1, 7 }, comp) << "\n"; return 0; }
输出:
-1
相关文章:
相关用法
注:本文由纯净天空筛选整理自 std::min in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。