std::partial_sort_copy

Header: <algorithm>

Sorts some of the elements in the range [first,last) in ascending order, storing the result in the range [d_first,d_last).

# Declarations

template< class InputIt, class RandomIt >
RandomIt partial_sort_copy( InputIt first, InputIt last,
RandomIt d_first, RandomIt d_last );

(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 );

(since C++17)

template< class InputIt, class RandomIt, class Compare >
RandomIt partial_sort_copy( InputIt first, InputIt last,
RandomIt d_first, RandomIt d_last,
Compare comp );

(constexpr since C++20)

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 );

(since C++17)

# Parameters

# Return value

An iterator to the element defining the upper boundary of the sorted range, i.e. d_first + std::min(std::distance(first, last), d_last - d_first).

# Example

#include <algorithm>
#include <functional>
#include <iostream>
#include <string_view>
#include <type_traits>
#include <vector>
 
void println(std::string_view rem, const auto& v)
{
    std::cout << rem;
    if constexpr (std::is_scalar_v<std::decay_t<decltype(v)>>)
        std::cout << v;
    else
        for (int e : v)
            std::cout << e << ' ';
    std::cout << '\n';
}
 
int main()
{
    const auto v0 = {4, 2, 5, 1, 3};
    std::vector<int> v1{10, 11, 12};
    std::vector<int> v2{10, 11, 12, 13, 14, 15, 16};
    std::vector<int>::iterator it;
 
    it = std::partial_sort_copy(v0.begin(), v0.end(), v1.begin(), v1.end());
    println("Writing to the smaller vector in ascending order gives: ", v1);
 
    if (it == v1.end())
        println("The return value is the end iterator", ' ');
 
    it = std::partial_sort_copy(v0.begin(), v0.end(), v2.begin(), v2.end(),
                                std::greater<int>());
 
    println("Writing to the larger vector in descending order gives: ", v2);
    println("The return value is the iterator to ", *it);
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
P0896R4C++98*first was not required to be writable to d_firstthe program is ill-formed if not writable

# See also