algorithm_max

algorithm_max (더 큰 값)

std::max는 주어진 값들 중 더 큰 값을 돌려줘요. 두 값 중 큰 값이나 이니셜라이저 리스트 중 최댓값을 구해요.

출처: cppreference

본문

std::max는 주어진 값들 중 더 큰 값을 반환해요. <algorithm> 헤더에 정의되어 있어요.

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

template< class T, class Compare >
const T& max( const T& a, const T& b, Compare comp );

template< class T >
T max( std::initializer_list<T> ilist );

template< class T, class Compare >
T max( std::initializer_list<T> ilist, Compare comp );
  • 1번 오버로드ab 중 큰 값을 돌려줘요. operator<로 비교하며 TLessThanComparable이어야 해요.
  • 2번 오버로드 — 비교 함수 comp로 비교해요.
  • 3번 오버로드 — 이니셜라이저 리스트 ilist의 값 중 가장 큰 값을 돌려줘요.
  • 4번 오버로드 — 비교 함수 comp로 비교해요.

반환값 (Return value)

두 값 중 더 큰 값, 또는 리스트의 최댓값이에요. 두 값이 같으면 a를 돌려줘요.

복잡도 (Complexity)

이니셜라이저 리스트 오버로드는 정확히 ilist.size() - 1번의 비교가 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>

int main()
{
    std::cout << "larger of 1 and 999: " << std::max(1, 999) << '\n'
              << "larger of 'a' and 'b': " << std::max('a', 'b') << '\n'
              << "largest of {2, 7, 3}: " << std::max({2, 7, 3}) << '\n';
}

출력:

larger of 1 and 999: 999
larger of 'a' and 'b': b
largest of {2, 7, 3}: 7

더 알아보기 (Learn more)

cppreference