Namespaces
Variants

std::ranges::partial_sort_copy, std::ranges::partial_sort_copy_result

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

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


 
제약 조건 알고리즘
이 메뉴의 모든 이름은 std::ranges
네임스페이스에 속함
(C++23)
unique_copy
stable_partition
partial_sort_copy
equal_range
set_symmetric_difference
pop_heap
clamp
prev_permutation
fold_left
fold_left_first  
fold_right
fold_right_last  
fold_left_with_iter
fold_left_first_with_iter
(C++23)
iota            
(C++23)
generate_random
(C++26)
uninitialized_value_construct_n
 
(C++23)<algorithm>
헤더
template< std::input_iterator I1, std::sentinel_for<I1> S1,
          std::random_access_iterator I2, std::sentinel_for<I2> S2,
          class Comp = ranges::less, class Proj1 = std::identity,
          class Proj2 = std::identity >
requires std::indirectly_copyable<I1, I2> &&
         std::sortable<I2, Comp, Proj2> &&
         std::indirect_strict_weak_order<Comp, std::projected<I1, Proj1>,
             std::projected<I2, Proj2>>
constexpr partial_sort_copy_result<I1, I2>
    partial_sort_copy( I1 first, S1 last, I2 result_first, S2 result_last,
                       Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} );
에 정의됨 호출 시그니처
template< ranges::input_range R1, ranges::random_access_range R2,
          class Comp = ranges::less, class Proj1 = std::identity,
          class Proj2 = std::identity >
requires std::indirectly_copyable<ranges::iterator_t<R1>, ranges::iterator_t<R2>> &&
         std::sortable<ranges::iterator_t<R2>, Comp, Proj2> &&
         std::indirect_strict_weak_order<Comp, std::projected<ranges::iterator_t<R1>,
             Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>>
constexpr partial_sort_copy_result<ranges::borrowed_iterator_t<R1>,
                                   ranges::borrowed_iterator_t<R2>>
    partial_sort_copy( R1&& r, R2&& result_r,
                       Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {} );
(1) (C++20부터)
(2)
template< class I, class O >
using partial_sort_copy_result = ranges::in_out_result<I, O>;
(C++20부터) 헬퍼 타입

(3) N(C++20부터)[first, last)소스 범위 comp에서 처음 proj1개의 요소를, [result_first, result_first + N) 및 로 복사합니다. 여기서 \(\scriptsize N = \min{(L_1, L_2)}\), \(\scriptsize L_1\)ranges::distance(first, last)L₁과 같고, \(\scriptsize L_2\)ranges::distance(result_first, result_last)L₂

는 과 같습니다. 동등한 요소들의 순서는 보존되지 않습니다.

1) 소스 범위 요소는 함수 객체 proj1을 사용하여 프로젝션되고, 대상 요소는 함수 객체 proj2을 사용하여 프로젝션됩니다.
2) (1)과 동일하지만, r을 소스 범위로, result_r을 대상 범위로 사용합니다. 이는 ranges::begin(r)을 first으로, ranges::end(r)을 last으로, ranges::begin(result_r)을 result_first으로, ranges::end(result_r)을 result_last으로 사용하는 것과 같습니다.

이 페이지에 설명된 함수형 개체는 알고리즘 함수 객체 (비공식적으로 niebloids라고 함)입니다. 즉:

  • 이들 중 하나를 호출할 때 명시적 템플릿 인자 목록을 지정할 수 없습니다.
  • 이들 중 어느 것도 인자 종속 조회에 보이지 않습니다.
  • 이들 중 어느 것이 일반 비한정 조회에 의해 함수 호출 연산자 왼쪽의 이름으로 발견되면, 인자 종속 조회가 억제됩니다.

매개변수

first, last - 복사할 원본 요소들의 범위 를 정의하는 반복자-센티널 쌍
r - 복사할 원본 범위
result_first, result_last - 대상 요소들의 범위 를 정의하는 반복자-센티널 쌍
result_r - 대상 범위
comp - 투영된 요소들에 적용할 비교 연산
proj1 - 원본 범위의 요소들에 적용할 투영 연산
proj2 - 대상 범위의 요소들에 적용할 투영 연산

반환값

{ last, result_first + N } 와 동일한 객체.

복잡도

최대 L₁•log(N) 번의 비교와 2•L₁•log(N) 번의 프로젝션이 필요합니다.

가능한 구현

struct partial_sort_copy_fn
{
    template<std::input_iterator I1, std::sentinel_for<I1> S1,
             std::random_access_iterator I2, std::sentinel_for<I2> S2,
             class Comp = ranges::less, class Proj1 = std::identity,
             class Proj2 = std::identity>
    requires std::indirectly_copyable<I1, I2> && std::sortable<I2, Comp, Proj2> &&
             std::indirect_strict_weak_order<Comp, std::projected<I1, Proj1>,
             std::projected<I2, Proj2>>
    constexpr ranges::partial_sort_copy_result<I1, I2>
        operator()(I1 first, S1 last, I2 result_first, S2 result_last,
                   Comp comp = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        if (result_first == result_last)
            return {std::move(ranges::next(std::move(first), std::move(last))),
                    std::move(result_first)};
        auto out_last{result_first};
        // 처음 N개 요소 복사
        for (; !(first == last or out_last == result_last); ++out_last, ++first)
            *out_last = *first;
        // N개의 복사된 요소를 최대 힙으로 변환
        ranges::make_heap(result_first, out_last, comp, proj2);
        // (존재하는 경우) 나머지 입력 범위를 힙 속성을 유지하며 처리
        for (; first != last; ++first)
        {
            if (std::invoke(comp, std::invoke(proj1, *first),
                                  std::invoke(proj2, *result_first)))
            {
                // 가장 큰 항목을 꺼내고 새로 발견된 더 작은 항목을 넣습니다
                ranges::pop_heap(result_first, out_last, comp, proj2);
                *(out_last - 1) = *first;
                ranges::push_heap(result_first, out_last, comp, proj2);
            }
        }
        // 출력 범위의 첫 N 요소는 여전히
        // 힙 - 정렬된 범위로 변환
        ranges::sort_heap(result_first, out_last, comp, proj2);
        return {std::move(first), std::move(out_last)};
    }
    template<ranges::input_range R1, ranges::random_access_range R2,
             class Comp = ranges::less, class Proj1 = std::identity,
             class Proj2 = std::identity>
    requires std::indirectly_copyable<ranges::iterator_t<R1>, ranges::iterator_t<R2>> &&
             std::sortable<ranges::iterator_t<R2>, Comp, Proj2> &&
             std::indirect_strict_weak_order<Comp, std::projected<ranges::iterator_t<R1>,
             Proj1>, std::projected<ranges::iterator_t<R2>, Proj2>>
    constexpr ranges::partial_sort_copy_result<ranges::borrowed_iterator_t
(설명: HTML 태그와 속성은 그대로 유지되었으며, C++ 관련 용어인 `ranges::borrowed_iterator_t`는 번역되지 않았습니다. 링크 구조와 클래스명이 원본 형식을 그대로 유지되었습니다.)<R1>,
              ranges::borrowed_iterator_t
(설명: HTML 태그와 속성은 그대로 유지되었으며, C++ 관련 용어인 `ranges::borrowed_iterator_t`는 번역되지 않았습니다. 링크 구조와 CSS 클래스도 원본 형식을 그대로 보존하였습니다.)<R2>>
        operator()(R1&& r, R2&& result_r, Comp comp = {},
                   Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r),
                       ranges::begin(result_r), ranges::end(result_r),
                       std::move(comp), std::move(proj1), std::move(proj2));
    }
};
inline constexpr partial_sort_copy_fn partial_sort_copy {};

예제

#include <algorithm>
#include <forward_list>
#include <functional>
#include <iostream>
#include <ranges>
#include <string_view>
#include <vector>
void print(std::string_view rem, std::ranges::input_range auto const& v)
{
    for (std::cout << rem; const auto& e : v)
        std::cout << e << ' ';
    std::cout << '\n';
}
int main()
{
    const std::forward_list source{4, 2, 5, 1, 3};
    print("Write to the smaller vector in ascending order: ", "");
    std::vector dest1{10, 11, 12};
    print("const source list: ", source);
    print("destination range: ", dest1);
    std::ranges::partial_sort_copy(source, dest1);
    print("partial_sort_copy: ", dest1);
    print("Write to the larger vector in descending order:", "");
    std::vector dest2{10, 11, 12, 13, 14, 15, 16};
    print("const source list: ", source);
    print("destination range: ", dest2);
    std::ranges::partial_sort_copy(source, dest2, std::greater{});
    print("partial_sort_copy: ", dest2);
}

출력:

Write to the smaller vector in ascending order:
const source list: 4 2 5 1 3
destination range: 10 11 12
partial_sort_copy: 1 2 3
Write to the larger vector in descending order:
const source list: 4 2 5 1 3
destination range: 10 11 12 13 14 15 16
partial_sort_copy: 5 4 3 2 1 15 16

같이 보기

범위의 처음 N개 요소를 정렬합니다
(알고리즘 함수 객체)
요소 범위를 정렬합니다
(알고리즘 함수 객체)
동등한 요소 간의 상대적 순서를 유지하면서 요소 범위를 정렬합니다
(알고리즘 함수 객체)
최대 힙을 정렬된 요소 범위로 변환합니다
(알고리즘 함수 객체)
요소 범위로부터 최대 힙을 생성합니다
(알고리즘 함수 객체)
최대 힙에 요소를 추가합니다
(알고리즘 함수 객체)
최대 힙에서 가장 큰 요소를 제거합니다
(알고리즘 함수 객체)
요소 범위를 복사하고 부분적으로 정렬합니다
(함수 템플릿)