Namespaces
Variants

std::ranges::minmax, std::ranges::minmax_result

cppreference.net에서
 
 
알고리즘 라이브러리
제약된 알고리즘 및 범위에 대한 알고리즘 (C++20)
제약된 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 탐색 연산
(분할된 범위에 대해)
집합 연산 (정렬된 범위에 대해)
병합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
제약된 알고리즘
이 메뉴의 모든 이름은 다음 네임스페이스에 속합니다: std::ranges
비수정 시퀀스 연산
수정 시퀀스 연산
분할 연산
정렬 연산
이진 탐색 연산 (정렬된 범위에 대해)
       
       
집합 연산 (정렬된 범위에 대해)
힙 연산
최소/최대 연산
       
       
순열 연산
폴드 연산
수치 연산
(C++23)            
초기화되지 않은 저장소에 대한 연산
반환 타입
 
헤더에 정의됨 <algorithm>
호출 시그니처
template< class T, class Proj = std::identity,
          std::indirect_strict_weak_order<
              std::projected<const T*, Proj>> Comp = ranges::less >
constexpr ranges::minmax_result<const T&>
    minmax( const T& a, const T& b, Comp comp = {}, Proj proj = {} );
(1) (since C++20)
template< std::copyable T, class Proj = std::identity,
          std::indirect_strict_weak_order<
              std::projected<const T*, Proj>> Comp = ranges::less >
constexpr ranges::minmax_result<T>
    minmax( std::initializer_list<T> r, Comp comp = {}, Proj proj = {} );
(2) (since C++20)
template< ranges::input_range R, class Proj = std::identity,
          std::indirect_strict_weak_order<
              std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less >
requires std::indirectly_copyable_storable<ranges::iterator_t<R>, ranges::range_value_t<R>*>
constexpr ranges::minmax_result<ranges::range_value_t<R>>
    minmax( R&& r, Comp comp = {}, Proj proj = {} );
(3) (since C++20)
헬퍼 타입
template< class T >
using minmax_result = ranges::min_max_result<T>;
(4) (since C++20)

주어진 투영된 값들 중 가장 작은 값과 가장 큰 값을 반환합니다.

1) 더 작은 값과 더 큰 값에 대한 참조를 반환합니다 a 및 b.
2) 이니셜라이저 리스트에 있는 값들 중 가장 작은 값과 가장 큰 값을 반환합니다 r.
3) 범위에 있는 값들 중 가장 작은 값과 가장 큰 값을 반환합니다 r.

오버로드 (2,3)에 대해, 범위가 빈 경우(다음에 의해 결정됨: ranges::distance(r)).\n

이 페이지에서 설명하는 함수형 엔티티는 알고리즘 함수 객체 (비공식적으로 niebloids), 즉:\n

매개변수

a, b - 비교할 값
r - 비교할 값들의 비어 있지 않은 범위
comp - 투영된 요소에 적용할 비교 연산
proj - 요소에 적용할 투영 연산

반환값

1) { b, a } 각각의 투영된 값에 따라 b 가 a 보다 작으면; 그렇지 않으면 { a, b } 를 반환합니다.
2,3) { s, l } , 여기서 s 와 l 는 각각 r 내에서 투영된 값에 따라 가장 작은 값과 가장 큰 값입니다. 여러 값이 가장 작거나 가장 큰 값과 동등한 경우, 가장 왼쪽의 가장 작은 값과 가장 오른쪽의 가장 큰 값을 반환합니다. 범위가 비어 있는 경우( ranges:: distance ( r ) 로 결정됨), 동작은 정의되지 않습니다.

복잡도

1) 정확히 한 번의 비교와 두 번의 프로젝션 적용.
2,3) 최대 3 / 2 * ranges:: distance ( r ) 번의 비교와 프로젝션의 두 배 적용.

가능한 구현

struct minmax_fn
{
    template<class T, class Proj = std::identity,
             std::indirect_strict_weak_order<
                 std::projected<const T*, Proj>> Comp = ranges::less>
    constexpr ranges::minmax_result<const T&>
         operator()(const T& a, const T& b, Comp comp = {}, Proj proj = {}) const
    {
        if (std::invoke(comp, std::invoke(proj, b), std::invoke(proj, a)))
            return {b, a};
        return {a, b};
    }
    template<std::copyable T, class Proj = std::identity,
             std::indirect_strict_weak_order<
                 std::projected<const T*, Proj>> Comp = ranges::less>
    constexpr ranges::minmax_result<T>
        operator()(std::initializer_list<T> r, Comp comp = {}, Proj proj = {}) const
    {
        auto result = ranges::minmax_element(r, std::ref(comp), std::ref(proj));
        return {*result.min, *result.max};
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirect_strict_weak_order<
                 std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less>
    requires std::indirectly_copyable_storable<ranges::iterator_t<R>,
                                               ranges::range_value_t<R>*>
    constexpr ranges::minmax_result<ranges::range_value_t<R>>
        operator()(R&& r, Comp comp = {}, Proj proj = {}) const
    {
        auto result = ranges::minmax_element(r, std::ref(comp), std::ref(proj));
        return {std::move(*result.min), std::move(*result.max)};
    }
};
inline constexpr minmax_fn minmax;

참고 사항

오버로드 (1) 의 경우, 매개변수 중 하나가 임시 객체인 경우, minmax 호출을 포함하는 전체 표현식의 끝에서 반환된 참조는 댕글링 참조가 됩니다:

int n = 1;
auto p = std::ranges::minmax(n, n + 1);
int m = p.min; // 정상
int x = p.max; // 정의되지 않은 동작
// 구조화된 바인딩도 동일한 문제가 있음
auto [mm, xx] = std::ranges::minmax(n, n + 1);
xx; // 정의되지 않은 동작

예제

#include <algorithm>
#include <array>
#include <iostream>
#include <random>
int main()
{
    namespace ranges = std::ranges;
    constexpr std::array v{3, 1, 4, 1, 5, 9, 2, 6, 5};
    std::random_device rd;
    std::mt19937_64 generator(rd());
    std::uniform_int_distribution<> distribution(0, ranges::distance(v)); // [0..9]
    // auto bounds = ranges::minmax(distribution(generator), distribution(generator));
    // UB: dangling references: bounds.min and bounds.max have the type `const int&`.
    const int x1 = distribution(generator);
    const int x2 = distribution(generator);
    auto bounds = ranges::minmax(x1, x2); // OK: got references to lvalues x1 and x2
    std::cout << "v[" << bounds.min << ":" << bounds.max << "]: ";
    for (int i = bounds.min; i < bounds.max; ++i)
        std::cout << v[i] << ' ';
    std::cout << '\n';
    auto [min, max] = ranges::minmax(v);
    std::cout << "smallest: " << min << ", " << "largest: " << max << '\n';
}

가능한 출력:

v[3:9]: 1 5 9 2 6 5 
smallest: 1, largest: 9

참고 항목

주어진 값들 중 더 작은 값을 반환합니다
(알고리즘 함수 객체)
주어진 값들 중 더 큰 값을 반환합니다
(알고리즘 함수 객체)
범위에서 가장 작은 요소와 가장 큰 요소를 반환합니다
(알고리즘 함수 객체)
값을 한 쌍의 경계값 사이로 고정합니다
(알고리즘 함수 객체)
(C++11)
두 요소 중 더 작은 값과 더 큰 값을 반환합니다
(함수 템플릿)