Movatterモバイル変換


[0]ホーム

URL:


cplusplus.com

Reference

<algorithm>

function template
<algorithm>

std::max

default (1)
template <class T> const T& max (const T& a, const T& b);
custom (2)
template <class T, class Compare>  const T& max (const T& a, const T& b, Compare comp);
default (1)
template <class T> const T& max (const T& a, const T& b);
custom (2)
template <class T, class Compare>  const T& max (const T& a, const T& b, Compare comp);
initializer list (3)
template <class T> T max (initializer_list<T> il);template <class T, class Compare>  T max (initializer_list<T> il, Compare comp);
default (1)
template <class T> constexpr const T& max (const T& a, const T& b);
custom (2)
template <class T, class Compare>  constexpr const T& max (const T& a, const T& b, Compare comp);
initializer list (3)
template <class T> constexpr T max (initializer_list<T> il);template <class T, class Compare>  constexpr T max (initializer_list<T> il, Compare comp);
Return the largest
Returns the largest ofa andb. If both are equivalent,a is returned.

The versions forinitializer lists (3) return the largest of all the elements in the list. Returning the first of them if these are more than one.

The function usesoperator< (orcomp, if provided) to compare the values.

The behavior of this function template (C++98) is equivalent to:
1
2
3
template <class T>const T& max (const T& a,const T& b) {return (a<b)?b:a;// or: return comp(a,b)?b:a; for version (2)}

Parameters

a, b
Values to compare.
comp
Binary function that accepts two values of typeT as arguments, and returns a value convertible tobool. 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.
il
Aninitializer_list object.
These objects are automatically constructed frominitializer list declarators.

T shall support being compared withoperator<.
For(3),T shall becopy constructible.

Return value

The largest of the values passed as arguments.

Example

1
2
3
4
5
6
7
8
9
10
11
// max example#include <iostream>// std::cout#include <algorithm>// std::maxint main () {  std::cout <<"max(1,2)==" << std::max(1,2) <<'\n';  std::cout <<"max(2,1)==" << std::max(2,1) <<'\n';  std::cout <<"max('a','z')==" << std::max('a','z') <<'\n';  std::cout <<"max(3.14,2.73)==" << std::max(3.14,2.73) <<'\n';return 0;}

Output:
max(1,2)==2max(2,1)==2max('a','z')==zmax(3.14,2.73)==3.14


Complexity

Linear in one less than the number of elements compared (constant for(1) and(2)).

Exceptions

Throws if any comparison throws.
Note that invalid arguments causeundefined behavior.

See also

min
Return the smallest(function template)
max_element
Return largest element in range(function template)
Home page |Privacy policy
© cplusplus.com, 2000-2025 - All rights reserved -v3.3.4s
Spotted an error? contact us

[8]ページ先頭

©2009-2026 Movatter.jp