Namespaces
Variants

std::ranges:: prev_permutation, std::ranges:: prev_permutation_result

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 Comp = ranges:: less , class Proj = std:: identity >
requires std:: sortable < I, Comp, Proj >
constexpr prev_permutation_result < I >

prev_permutation ( I first, S last, Comp comp = { } , Proj proj = { } ) ;
(1) (C++20 이후)
template < ranges:: bidirectional_range R, class Comp = ranges:: less ,

class Proj = std:: identity >
requires std:: sortable < ranges:: iterator_t < R > , Comp, Proj >
constexpr prev_permutation_result < ranges:: borrowed_iterator_t < R >>

prev_permutation ( R && r, Comp comp = { } , Proj proj = { } ) ;
(2) (C++20 이후)
헬퍼 타입
template < class I >
using prev_permutation_result = ranges:: in_found_result < I > ;
(3) (C++20 이후)
1) 범위 [ first , last ) 를 이전 순열 로 변환합니다. 여기서 모든 순열의 집합은 이진 비교 함수 객체 comp 와 투영 함수 객체 proj 에 대해 사전식 순서 로 정렬됩니다.
반환값:
  • { last, true } "이전" 순열이 존재하는 경우. 그렇지 않으면,
  • { last, false } 를 반환하고, 범위를 (사전식 순서로) 마지막 순열로 변환합니다. 마치 다음과 같이 수행한 것처럼:
ranges::sort(first, last, comp, proj);
ranges::reverse(first, last);
2) (1) 과 동일하지만, r 을 소스 범위로 사용하며, 마치 ranges:: begin ( r ) first 로, ranges:: end ( r ) last 로 사용하는 것과 같습니다.

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

목차

매개변수

first, last - "순열"할 요소들의 범위 를 정의하는 반복자-감시자 쌍
r - "순열"할 요소들의 range 범위
comp - 첫 번째 인수가 두 번째 인수보다 작으면 true 를 반환하는 비교 FunctionObject
proj - 요소에 적용할 투영(projection)

반환값

1) ranges :: prev_permutation_result < I > { last, true } 새로운 순열이 이전 순열보다 사전순으로 작은 경우. ranges :: prev_permutation_result < I > { last, false } 첫 번째 순열에 도달하고 범위가 마지막 순열로 재설정된 경우.
2) (1) 과 동일하지만 반환 타입이 ranges :: prev_permutation_result < ranges:: borrowed_iterator_t < R >> 입니다.

예외

반복자 연산 또는 요소 교체에서 발생하는 모든 예외.

복잡도

최대 N / 2 회의 교환, 여기서 N ranges:: distance ( first, last ) (경우 (1) ) 또는 ranges:: distance ( r ) (경우 (2) )입니다. 전체 순열 시퀀스에 걸쳐 평균적으로, 일반적인 구현은 호출당 약 3회의 비교와 1.5회의 교환을 사용합니다.

참고 사항

구현체들(예: MSVC STL )은 반복자 타입이 contiguous_iterator 를 모델링하고, 그 값 타입의 스왑 연산이 비트리비얼 특수 멤버 함수나 ADL 에 의해 발견된 swap 을 호출하지 않을 때 벡터화를 활성화할 수 있습니다.

가능한 구현

struct prev_permutation_fn
{
    template<std::bidirectional_iterator I, std::sentinel_for<I> S,
             class Comp = ranges::less, class Proj = std::identity>
    requires std::sortable<I, Comp, Proj>
    constexpr ranges::prev_permutation_result<I>
        operator()(I first, S last, Comp comp = {}, Proj proj = {}) const
    {
        // 시퀀스에 최소 두 개의 요소가 있는지 확인
        if (first == last)
            return {std::move(first), false};
        auto i{first};
        ++i;
        if (i == last)
            return {std::move(i), false};
        auto i_last{ranges::next(first, last)};
        i = i_last;
        --i;
        // 주요 "순열 생성" 루프
        for (;;)
        {
            auto i1{i};
            --i;
            if (std::invoke(comp, std::invoke(proj, *i1), std::invoke(proj, *i)))
            {
                auto j{i_last};
                while (!std::invoke(comp, std::invoke(proj, *--j), std::invoke(proj, *i)))
                    ;
                ranges::iter_swap(i, j);
                ranges::reverse(i1, last);
                return {std::move(i_last), true};
            }
            // 순열 "공간"이 소진됨
            if (i == first)
            {
                ranges::reverse(first, last);
                return {std::move(i_last), false};
            }
        }
    }
    template<ranges::bidirectional_range R, class Comp = ranges::less,
             class Proj = std::identity>
    requires std::sortable<ranges::iterator_t<R>, Comp, Proj>
    constexpr ranges::prev_permutation_result<ranges::borrowed_iterator_t<R>>
        operator()(R&& r, Comp comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r),
                       std::move(comp), std::move(proj));
    }
};
inline constexpr prev_permutation_fn prev_permutation {};

예제

#include <algorithm>
#include <array>
#include <compare>
#include <functional>
#include <iostream>
#include <string>
struct S
{
    char c{};
    int i{};
    auto operator<=>(const S&) const = default;
    friend std::ostream& operator<<(std::ostream& os, const S& s)
    {
        return os << "{'" << s.c << "', " << s.i << "}";
    }
};
auto print = [](auto const& v, char term = ' ')
{
    std::cout << "{ ";
    for (const auto& e : v)
        std::cout << e << ' ';
    std::cout << '}' << term;
};
int main()
{
    std::cout << "Generate all permutations (iterators case):\n";
    std::string s{"cba"};
    do print(s);
    while (std::ranges::prev_permutation(s.begin(), s.end()).found);
    std::cout << "\nGenerate all permutations (range case):\n";
    std::array a{'c', 'b', 'a'};
    do print(a);
    while (std::ranges::prev_permutation(a).found);
    std::cout << "\nGenerate all permutations using comparator:\n";
    using namespace std::literals;
    std::array z{"▁"s, "▄"s, "█"s};
    do print(z);
    while (std::ranges::prev_permutation(z, std::greater()).found);
    std::cout << "\nGenerate all permutations using projection:\n";
    std::array<S, 3> r{S{'C',1}, S{'B',2}, S{'A',3}};
    do print(r, '\n');
    while (std::ranges::prev_permutation(r, {}, &S::c).found);
}

출력:

Generate all permutations (iterators case):
{ c b a } { c a b } { b c a } { b a c } { a c b } { a b c }
Generate all permutations (range case):
{ c b a } { c a b } { b c a } { b a c } { a c b } { a b c }
Generate all permutations using comparator:
{ ▁ ▄ █ } { ▁ █ ▄ } { ▄ ▁ █ } { ▄ █ ▁ } { █ ▁ ▄ } { █ ▄ ▁ }
Generate all permutations using projection:
{ {'C', 1} {'B', 2} {'A', 3} }
{ {'C', 1} {'A', 3} {'B', 2} }
{ {'B', 2} {'C', 1} {'A', 3} }
{ {'B', 2} {'A', 3} {'C', 1} }
{ {'A', 3} {'C', 1} {'B', 2} }
{ {'A', 3} {'B', 2} {'C', 1} }

참고 항목

원소 범위의 다음으로 큰 사전식 순열을 생성합니다
(알고리즘 함수 객체)
시퀀스가 다른 시퀀스의 순열인지 확인합니다
(알고리즘 함수 객체)
원소 범위의 다음으로 큰 사전식 순열을 생성합니다
(함수 템플릿)
원소 범위의 다음으로 작은 사전식 순열을 생성합니다
(함수 템플릿)
시퀀스가 다른 시퀀스의 순열인지 확인합니다
(함수 템플릿)