algorithm_minmax_element

algorithm_minmax_element (최소·최대 요소 찾기)

std::minmax_element는 대상 범위에서 가장 작은 요소와 가장 큰 요소를 한 번에 찾아 반복자 쌍으로 돌려줘요.

출처: cppreference

본문

std::minmax_element는 대상 범위 [first, last)에서 가장 작은 요소와 가장 큰 요소를 찾아 std::pair로 돌려줘요. <algorithm> 헤더에 정의되어 있어요.

template< class ForwardIt >
std::pair<ForwardIt, ForwardIt>
    minmax_element( ForwardIt first, ForwardIt last );

template< class ForwardIt, class Compare >
std::pair<ForwardIt, ForwardIt>
    minmax_element( ForwardIt first, ForwardIt last, Compare comp );
  • 1번 오버로드 — 요소를 operator<(즉 std::less{})로 비교해요.
  • 2번 오버로드 — 요소를 비교 함수 comp로 비교해요.
  • 병렬 실행 정책을 받는 오버로드도 있어요.

반환값 (Return value)

가장 작은 요소와 가장 큰 요소를 가리키는 반복자 쌍이에요. 범위가 비어 있으면 (last, last)를 돌려줘요.

복잡도 (Complexity)

Nstd::distance(first, last)라고 하면 최대 max(3/2·(N - 1), 0)번의 비교가 필요해요.

예제 (Example)

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6};
    auto [min, max] = std::minmax_element(v.begin(), v.end());
    std::cout << "min: " << *min << ", max: " << *max << '\n';
}

출력:

min: 1, max: 9

더 알아보기 (Learn more)

cppreference