std::partial_sort_copy - cppreference.com
Namespaces
Variants

std::partial_sort_copy

From cppreference.com
 
 
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy, ranges::sort, ...
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
(C++11)    

Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
(C++11)
(C++17)
Lexicographical comparison operations
Permutation operations


 
Defined in header <algorithm>
template< class InputIt, class RandomIt >
RandomIt partial_sort_copy( InputIt first, InputIt last,
                            RandomIt d_first, RandomIt d_last );
(1) (constexpr since C++20)
template< class InputIt, class RandomIt, class Compare >
RandomIt partial_sort_copy( InputIt first, InputIt last,
                            RandomIt d_first, RandomIt d_last,
                            Compare comp );
(2) (constexpr since C++20)
template< class ExecutionPolicy,
          class ForwardIt, class RandomIt >
RandomIt partial_sort_copy( ExecutionPolicy&& policy,
                            ForwardIt first, ForwardIt last,
                            RandomIt d_first, RandomIt d_last );
(3) (since C++17)
template< class ExecutionPolicy,
          class ForwardIt, class RandomIt, class Compare >
RandomIt partial_sort_copy( ExecutionPolicy&& policy,
                            ForwardIt first, ForwardIt last,
                            RandomIt d_first, RandomIt d_last,
                            Compare comp );
(4) (since C++17)

Copies elements from the source range [firstlast) as sorted into the destination range [d_firstd_last):

  • If std::distance(first, last) is greater than d_last - d_first, the first d_last - d_first elements of the source range is copied as sorted into [d_firstd_last).
  • Otherwise, all elements of the source range is copied as sorted into [d_firstd_first + std::distance(first, last)).
1) Elements are sorted with respect to operator<(until C++20)std::less{}(since C++20).
2) Elements are sorted with respect to comp.
3,4) Same as (1,2), but executed according to policy.
These overloads participate in overload resolution only if the value of the following expression is true:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(until C++20)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(since C++20)

If *first is not writable to d_first, the program is ill-formed.

If any of the following conditions is satisfied, the behavior is undefined:

(until C++11)
(since C++11)

Parameters

first, last - the pair of iterators defining the source range
d_first, d_last - the pair of iterators defining the destination range
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second.

The signature of the comparison function should be equivalent to the following:

bool cmp(const Type1& a, const Type2& b);

While the signature does not need to have const&, the function must not modify the objects passed to it and must be able to accept all values of type (possibly const) Type1 and Type2 regardless of value category (thus, Type1& is not allowed, nor is Type1 unless for Type1 a move is equivalent to a copy(since C++11)).
The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ​

policy - the execution policy to use
Type requirements
-
InputIt must meet the requirements of LegacyInputIterator.
-
ForwardIt must meet the requirements of LegacyForwardIterator.
-
RandomIt must meet the requirements of LegacyRandomAccessIterator.
-
Compare must meet the requirements of Compare.

Return value

An iterator past the last assigned element in the destination range, or d_first if no element is assigned.

Complexity

Given

  • N1 as std::distance(first, last),
  • N2 as d_last - d_first:
1) Approximately N1·log(min(N1,N2)) comparisons using operator<(until C++20)std::less{}(since C++20).
2) Approximately N1·log(min(N1,N2)) applications of the comparator comp.
3) 𝓞(N1·log(min(N1,N2))) comparisons using operator<(until C++20)std::less{}(since C++20).
4) 𝓞(N1·log(min(N1,N2))) applications of the comparator comp.

Exceptions

3,4) During the execution process:
  • If the temporary memory resources required for parallelization are not available, std::bad_alloc is thrown.
  • If an uncaught exception is thrown while accessing objects via an algorithm argument, the behavior is determined by the execution policy (for standard policies, std::terminate is invoked).

Possible implementation

See also the implementations in libstdc++ and libc++.

Example

#include <algorithm>
#include <cstdio>
#include <functional>
#include <print>
#include <string_view>

struct Result
{
    std::string_view name;
    double score;

    friend std::partial_ordering operator<=>(Result lhs, Result rhs)
    {
        return lhs.score <=> rhs.score;
    }
};

int main()
{
    const Result results[]
    {
        {"Curt von Bardeleben", 11.5},
        {"Emanuel Lasker",      15.5},
        {"Emanuel Schiffers",   12},
        {"Harry Pillsbury",     16.5},
        {"Mikhail Chigorin",    16},
        {"Richard Teichmann",   11.5},
        {"Siegbert Tarrasch",   14},
        {"William Steinitz",    13}
    };

    Result podium[3];
    std::partial_sort_copy(
        std::begin(results), std::end(results),
        std::begin(podium), std::end(podium),
        std::greater()
    );

    std::puts("Top 3:");
    for (Result result : podium)
        std::print("    {}: {}\n", result.name, result.score);
}

Output:

Top 3:
    Harry Pillsbury: 16.5
    Mikhail Chigorin: 16
    Emanuel Lasker: 15.5

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
P0896R4 C++98 *first was not required to be writable to d_first the program is ill-formed if not writable

See also