How to use min() function in C++

This tutorial will teach us how to use the min() function in C++.

Description

min() function in c++ returns us the smaller value by comparing the passed parameters.

If both parameters are equal, it returns the first value.

Header Files

We require only two header files over here.

#include<iostream> (Standard input-output)

#include<alogithm> (for declaring min function)

Syntax

min(argument 1, argument 2)

argument 1=First value to be compared.

argument 2=Second value to be compared.

Return Value

It returns the value which is smaller among argument 1 and argument 2.

Complexity

Linear complexity.

Code

The sample code is as follows…

#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
    int a,b;
    cout<<"Enter the value of a and b\n";
    cin>>a>>b;
    int res=min(a,b);
    cout<<"The smaller element is "<<res;
    return 0;
}

Output :

Enter the value of a and b
4
8
The smaller element is 4

Explanation…

  1. First, we need to take the arguments(argument1, argument2) from the user.
  2. Then, we need to put those arguments in the min function and need to store that in an variable(i.e… res).
  3. Then, that res value stores the minimum value.

This, min function can also be used for finding the minimum element from the list.

The sample code is as follows…

#include <iostream>
#include<algorithm>
using namespace std;
bool comp(int x,int y)
{
    return (x<y);
}
int main()
{
    int res=min({45,3489,54,93},comp);
    cout<<"The smaller element is "<<res;
    return 0;
}

Output :

The smaller element is 45

Explanation…

  1. Even here we have two arguments that need to be filled, one is for the list and another is the function name.
  2. After declaring in the min function that calls a comparison function.
  3. That particular function returns only if x is <  y as x and y are the parameters of the comparison function.

 

Leave a Reply

Your email address will not be published. Required fields are marked *