Namespaces
Variants

std::ranges:: partition

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:: permutable I, std:: sentinel_for < I > S, class Proj = std:: identity ,

std:: indirect_unary_predicate < std :: projected < I, Proj >> Pred >
constexpr ranges:: subrange < I >

partition ( I first, S last, Pred pred, Proj proj = { } ) ;
(1) (C++20부터)
template < ranges:: forward_range R, class Proj = std:: identity ,

std:: indirect_unary_predicate <
std :: projected < ranges:: iterator_t < R > , Proj >> Pred >
requires std:: permutable < ranges:: iterator_t < R >>
constexpr ranges:: borrowed_subrange_t < R >

partition ( R && r, Pred pred, Proj proj = { } ) ;
(2) (C++20부터)
1) 범위 [ first , last ) 내의 요소들을 재배열하여, predicate pred true 를 반환하는 모든 요소들의 projection proj 가 predicate pred false 를 반환하는 요소들의 projection proj 앞에 오도록 합니다. 요소들의 상대적 순서는 유지되지 않습니다.
2) (1) 과 동일하지만, r 을 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

이 페이지에서 설명하는 함수형 개체들은 algorithm function objects (일반적으로 niebloids 로 알려진)입니다. 즉:

목차

매개변수

first, last - 요소를 재정렬할 범위 를 정의하는 반복자-감시자 쌍
r - 재정렬할 요소들의 범위
pred - 투영된 요소들에 적용할 조건자
proj - 요소들에 적용할 투영

반환값

두 번째 그룹의 첫 번째 요소를 가리키는 반복자로 시작하고 last 와 동일한 반복자로 끝나는 하위 범위. (2) r 이 non- borrowed_range 타입의 rvalue인 경우 std::ranges::dangling 을 반환합니다.

복잡도

주어진 N = ranges:: distance ( first, last ) 에 대해, 술어와 프로젝션을 정확히 N 번 적용합니다. I ranges::bidirectional_iterator 를 모델링하는 경우 최대 N / 2 번의 교환이 발생하며, 그렇지 않은 경우 최대 N 번의 교환이 발생합니다.

가능한 구현

struct partition_fn
{
    template<std::permutable I, std::sentinel_for<I> S, class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr ranges::subrange<I>
        operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        first = ranges::find_if_not(first, last, std::ref(pred), std::ref(proj));
        if (first == last)
            return {first, first};
        for (auto i = ranges::next(first); i != last; ++i)
        {
            if (std::invoke(pred, std::invoke(proj, *i)))
            {
                ranges::iter_swap(i, first);
                ++first;
            }
        }
        return {std::move(first), std::move(last)};
    }
    template<ranges::forward_range R, class Proj = std::identity,
             std::indirect_unary_predicate<
                 std::projected<ranges::iterator_t<R>, Proj>> Pred>
    requires std::permutable<ranges::iterator_t<R>>
    constexpr ranges::borrowed_subrange_t<R>
        operator()(R&& r, Pred pred, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r),
                       std::ref(pred), std::ref(proj));
    }
};
inline constexpr partition_fn partition;

예제

#include <algorithm>
#include <forward_list>
#include <functional>
#include <iostream>
#include <iterator>
#include <ranges>
#include <vector>
namespace ranges = std::ranges;
template<class I, std::sentinel_for<I> S, class Cmp = ranges::less>
requires std::sortable<I, Cmp>
void quicksort(I first, S last, Cmp cmp = Cmp {})
{
    using reference = std::iter_reference_t<I>;
    if (first == last)
        return;
    auto size = ranges::distance(first, last);
    auto pivot = ranges::next(first, size - 1);
    ranges::iter_swap(pivot, ranges::next(first, size / 2));
    auto tail = ranges::partition(first, pivot, [=](reference em)
    {
        return std::invoke(cmp, em, *pivot); // em < pivot
    });
    ranges::iter_swap(pivot, tail.begin());
    quicksort(first, tail.begin(), std::ref(cmp));
    quicksort(ranges::next(tail.begin()), last, std::ref(cmp));
}
int main()
{
    std::ostream_iterator<int> cout {std::cout, " "};
    std::vector<int> v {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::cout << "원본 벡터:  \t";
    ranges::copy(v, cout);
    auto tail = ranges::partition(v, [](int i) { return i % 2 == 0; });
    std::cout << "\n분할된 벡터: \t";
    ranges::copy(ranges::begin(v), ranges::begin(tail), cout);
    std::cout << "│ ";
    ranges::copy(tail, cout);
    std::forward_list<int> fl {1, 30, -4, 3, 5, -4, 1, 6, -8, 2, -5, 64, 1, 92};
    std::cout << "\n정렬되지 않은 목록: \t\t";
    ranges::copy(fl, cout);
    quicksort(ranges::begin(fl), ranges::end(fl), ranges::greater {});
    std::cout << "\n퀵 정렬된 리스트: \t";
    ranges::copy(fl, cout);
    std::cout << '\n';
}

가능한 출력:

원본 벡터:        0 1 2 3 4 5 6 7 8 9
분할된 벡터:     0 8 2 6 4 │ 5 3 7 1 9
정렬되지 않은 리스트:          1 30 -4 3 5 -4 1 6 -8 2 -5 64 1 92
퀵 정렬된 리스트:      92 64 30 6 5 3 2 1 1 1 -4 -4 -5 -8

참고 항목

범위의 요소들을 두 그룹으로 나누어 복사합니다
(알고리즘 함수 객체)
주어진 조건자에 의해 범위가 분할되었는지 확인합니다
(알고리즘 함수 객체)
요소들의 상대적 순서를 유지하면서 두 그룹으로 분할합니다
(알고리즘 함수 객체)
요소들의 범위를 두 그룹으로 분할합니다
(함수 템플릿)