std::min in C++
std::min is defined in the header file <algorithm> and is used to find out the smallest of the number passed to it. It returns the first of them, if there are more than one.
It can be used in following 3 manners:
- It compares the two numbers passed in its arguments and returns the smaller of the two, and if both are equal, then it returns the first one.
- It can also compare the two numbers using a binary function , which is defined by the user, and then passed as argument in std::min().
- It is also useful if we want to find the smallest element in a given list, and it returns the first one if there are more than one present in the list.
The three versions are as defined below:
- For comparing elements using < :
template constexpr const T& min (const T& a, const T& b); a and b are the numbers to be compared. Returns: Smaller of the two values.
- For comparing elements using a pre-defined function:
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. Returns: Smaller of the two values.
- For finding the minimum element in a list:
template constexpr T min (initializer_list il, Compare comp); comp is optional and can be skipped. il: An initializer_list object. Returns: Smallest of all the values.
This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.