Daily bit(e) C++ #87, Алгоритм частичной сортировки, который может работать с входными диапазонами: std::partial_sort_copy

Большинство алгоритмов сортировки в стандартной библиотеке требуют, чтобы исходный диапазон был диапазоном произвольного доступа.

Однако алгоритм std::partial_sort_copy выделяется из общего ряда, поскольку он может работать с входными диапазонами.

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

std::vector<int> top_five(5);

std::partial_sort_copy(
    // iterate over integers on standard input until reaching EOF
    std::istream_iterator<int>(std::cin), std::istream_iterator<int>{},
    // destination range is still required to be a random access
    top_five.begin(), top_five.end(),
    // default order is non-descending; make it non-ascending
    std::greater<int>{});

// For standard input: 9 1 3 4 2 7 8 6 5
// top_five == {9, 8, 7, 6, 5}

Откройте пример в Compiler Explorer.