Namespaces
Variants

std::ranges:: stable_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:: bidirectional_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
std:: indirect_unary_predicate < std :: projected < I, Proj >> Pred >
requires std:: permutable < I >
ranges:: subrange < I >

stable_partition ( I first, S last, Pred pred, Proj proj = { } ) ;
(1) (C++20부터)
(C++26부터 constexpr)
template < ranges:: bidirectional_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 >>
ranges:: borrowed_subrange_t < R >

stable_partition ( R && r, Pred pred, Proj proj = { } ) ;
(2) (C++20부터)
(C++26부터 constexpr)
1) [ first , last ) 범위의 요소들을 재정렬하여, pred 술어가 true 를 반환하는 모든 요소들의 proj 투영이 pred 술어가 false 를 반환하는 요소들의 proj 투영 앞에 오도록 합니다. 이 알고리즘은 stable 하므로, 요소들의 상대적 순서가 보존됩니다 .
2) (1) 와 동일하지만, r 를 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

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

목차

매개변수

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

반환값

1) 두 번째 그룹의 첫 번째 요소를 가리키는 반복자인 pivot last 가 같은 객체 { pivot, last } 입니다.
2) (1) 과 동일하되, r 이 lvalue이거나 borrowed_range 타입인 경우. 그렇지 않으면 std::ranges::dangling 을 반환합니다.

복잡도

주어진 N = ranges:: distance ( first, last ) , 최악의 경우 복잡도는 N·log(N) 회의 교환(swap)이며, 추가 메모리 버퍼가 사용되는 경우에는 𝓞(N) 회의 교환만 발생합니다. 술어(predicate) pred 와 투영(projection) proj 는 정확히 N 회 적용됩니다.

참고 사항

이 함수는 임시 버퍼 할당을 시도합니다. 할당이 실패할 경우, 덜 효율적인 알고리즘이 선택됩니다.

기능 테스트 매크로 표준 기능
__cpp_lib_constexpr_algorithms 202306L (C++26) constexpr 안정 정렬

가능한 구현

이 구현은 추가 메모리 버퍼를 사용하지 않으므로 효율성이 낮을 수 있습니다. 또한 MSVC STL libstdc++ 의 구현도 참조하십시오.

struct stable_partition_fn
{
    template<std::bidirectional_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    requires std::permutable<I>
    constexpr ranges::subrange<I>
        operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        first = ranges::find_if_not(first, last, pred, proj);
        I mid = first;
        while (mid != last)
        {
            mid = ranges::find_if(mid, last, pred, proj);
            if (mid == last)
                break;
            I last2 = ranges::find_if_not(mid, last, pred, proj);
            ranges::rotate(first, mid, last2);
            first = ranges::next(first, ranges::distance(mid, last2));
            mid = last2;
        }
        return {std::move(first), std::move(mid)};
    }
    template<ranges::bidirectional_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::move(pred), std::move(proj));
    }
};
inline constexpr stable_partition_fn stable_partition {};

예제

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
namespace rng = std::ranges;
template<std::permutable I, std::sentinel_for<I> S>
constexpr void stable_sort(I first, S last)
{
    if (first == last)
        return;
    auto pivot = *rng::next(first, rng::distance(first, last) / 2, last);
    auto left = [pivot](const auto& em) { return em < pivot; };
    auto tail1 = rng::stable_partition(first, last, left);
    auto right = [pivot](const auto& em) { return !(pivot < em); };
    auto tail2 = rng::stable_partition(tail1, right);
    stable_sort(first, tail1.begin());
    stable_sort(tail2.begin(), tail2.end());
}
void print(const auto rem, auto first, auto last, bool end = true)
{
    std::cout << rem;
    for (; first != last; ++first)
        std::cout << *first << ' ';
    std::cout << (end ? "\n" : "");
}
int main()
{
    const auto original = {9, 6, 5, 2, 3, 1, 7, 8};
    std::vector<int> vi {};
    auto even = [](int x) { return 0 == (x % 2); };
    print("Original vector:\t", original.begin(), original.end(), "\n");
    vi = original;
    const auto ret1 = rng::stable_partition(vi, even);
    print("Stable partitioned:\t", vi.begin(), ret1.begin(), 0);
    print("│ ", ret1.begin(), ret1.end());
    vi = original;
    const auto ret2 = rng::partition(vi, even);
    print("Partitioned:\t\t", vi.begin(), ret2.begin(), 0);
    print("│ ", ret2.begin(), ret2.end());
    vi = {16, 30, 44, 30, 15, 24, 10, 18, 12, 35};
    print("Unsorted vector: ", vi.begin(), vi.end());
    stable_sort(rng::begin(vi), rng::end(vi));
    print("Sorted vector:   ", vi.begin(), vi.end());
}

가능한 출력:

Original vector:        9 6 5 2 3 1 7 8
Stable partitioned:     6 2 8 │ 9 5 3 1 7
Partitioned:            8 6 2 │ 5 3 1 7 9
Unsorted vector: 16 30 44 30 15 24 10 18 12 35
Sorted vector:   10 12 15 16 18 24 30 30 35 44

참고 항목

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