What is the min() Function and How it Works in C++?
The min() function compares passed parameters to determine their minimum. If the two values are equivalent, the first value is returned. The min() function has many variations that apply to values as well as initializer lists. The header <algorithm> is required for this function. One can find the syntax to declare the min() function in C++ as follows:
Syntax
Here num_1 and num_2 are numbers that are used to being compared. It gives the smaller of the two values num_1 and num_2.
Example 1
Let’s consider some examples that describe the working of the min() function.
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "minimum of 5 and 54 is: " << min(5, 54)<<endl;
cout << "minimum of 0.7 and 0.9 is: "<< min(0.7,0.9)<<endl;
cout << "minimum of 10 and -10 is: " << min(10,-10)<<endl;
cout << "minimum of x and a is: " << min('x','a')<<endl;
return 0;
}
In the above example, we demonstrate the use of the min() function in C++ on different data types like int, char and float values. We also compared the numbers having opposite signs like 10 and -10.
Output
Example 2
This min() function additionally has the ability to identify the smallest element in a list. The following is an example of code:
#include<algorithm>
using namespace std;
int main()
{
int small_num=min({349,54,78});
cout<<"The smallest value is: "<<small_num;
return 0;
}
The result has been printed to the console.
Output
Conclusion
The min() function is a useful function in C++ that allows you to find the minimum value among a set of values. It is a pre-built function in C++ standard library that users can use by declaring the <algorithm> header file. The above guide presents simple examples to use min() function in C++. It will help the beginners to learn basics of this function.