Namespaces
Variants

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

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
헤더 파일에 정의됨 <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 = { } ) ;
(1) (C++20부터)
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 = { } ) ;
(2) (C++20 이후)
헬퍼 타입
template < class I, class O >
using partial_sort_copy_result = ranges:: in_out_result < I, O > ;
(3) (C++20 이후)

소스 범위 [ first , last ) 에서 처음 N 개의 요소를 comp proj1 에 대해 부분적으로 정렬된 것처럼 대상 범위 [ result_first , result_first + N ) 로 복사합니다. 여기서 N = min(L₁, L₂) , L₁ ranges:: distance ( first, last ) 와 같고, L₂ ranges:: distance ( result_first, result_last ) 와 같습니다.

동일한 요소들의 순서는 보장되지 않습니다.

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 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 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개 요소를 정렬
(알고리즘 함수 객체)
범위를 오름차순으로 정렬
(알고리즘 함수 객체)
동일한 요소들 사이의 순서를 유지하며 범위 정렬
(알고리즘 함수 객체)
최대 힙을 오름차순으로 정렬된 요소 범위로 변환
(알고리즘 함수 객체)
요소 범위로부터 최대 힙 생성
(알고리즘 함수 객체)
최대 힙에 요소 추가
(알고리즘 함수 객체)
최대 힙에서 가장 큰 요소 제거
(알고리즘 함수 객체)
요소 범위를 복사하고 부분적으로 정렬
(함수 템플릿)