Home > Backend Development > C++ > How to use min function in c++

How to use min function in c++

下次还敢
Release: 2024-05-09 01:15:24
Original
1130 people have browsed it

min function is used to compare the minimum of two or more values. It takes arguments a and b and returns the smallest of them. If you use comparator comp, you can customize the comparison rules. The min function can also be used to compare multiple values ​​by passing them as function arguments.

How to use min function in c++

Usage of min function in c

Introduction to min function

## The #min function is a standard library function used to compare the minimum of two or more values. It accepts two or more parameters and returns the smallest value among them.

Function Syntax

<code class="cpp">#include <algorithm>

template<class T>
const T& min(const T& a, const T& b);

template<class T, class Compare>
const T& min(const T& a, const T& b, Compare comp);</code>
Copy after login

Parameters

  • a and b : Two or more values ​​to compare.
  • comp: Optional comparator for custom comparison rules (only the second function prototype exists).

Return type

#min The function return type is the same as the parameter type, representing the minimum value.

Usage example

Compare the minimum value of two numbers:

<code class="cpp">int a = 10;
int b = 5;

int min_value = min(a, b); // min_value 为 5</code>
Copy after login
Use a comparator to customize the comparison rule:

<code class="cpp">struct MyComparator {
    bool operator()(const int& a, const int& b) {
        return a > b;
    }
};

int a = 10;
int b = 5;

int max_value = min(a, b, MyComparator()); // max_value 为 10</code>
Copy after login

Note:

    If two or more values ​​are equal, the
  • min function will return the first parameter.
  • min Functions can also be used to compare multiple values ​​by passing them as function arguments.

The above is the detailed content of How to use min function in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template