Namespaces
Variants

std::ranges:: is_permutation

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:: forward_iterator I1, std:: sentinel_for < I1 > S1,

std:: forward_iterator I2, std:: sentinel_for < I2 > S2,
class Proj1 = std:: identity , class Proj2 = std:: identity ,
std:: indirect_equivalence_relation < std :: projected < I1, Proj1 > ,
std :: projected < I2, Proj2 >>
Pred = ranges:: equal_to >
constexpr bool
is_permutation ( I1 first1, S1 last1, I2 first2, S2 last2, Pred pred = { } ,

Proj1 proj1 = { } , Proj2 proj2 = { } ) ;
(1) (C++20 이후)
template < ranges:: forward_range R1, ranges:: forward_range R2,

class Proj1 = std:: identity , class Proj2 = std:: identity ,
std:: indirect_equivalence_relation <
std :: projected < ranges:: iterator_t < R1 > , Proj1 > ,
std :: projected < ranges:: iterator_t < R2 > , Proj2 >>
Pred = ranges:: equal_to >
constexpr bool
is_permutation ( R1 && r1, R2 && r2, Pred pred = { } ,

Proj1 proj1 = { } , Proj2 proj2 = { } ) ;
(2) (C++20 이후)
1) 범위 [ first1 , last1 ) 의 요소들을 순열 하여 (해당 투영 함수 Proj1 , Proj2 를 적용하고 이항 조건자 Pred 를 비교자로 사용한 후) 범위 [ first2 , last2 ) 동일하게 만들 수 있으면 true 를 반환합니다. 그렇지 않으면 false 를 반환합니다.
2) (1) 과 동일하지만, r1 을 첫 번째 소스 범위로, r2 를 두 번째 소스 범위로 사용합니다. 마치 ranges:: begin ( r1 ) first1 으로, ranges:: end ( r1 ) last1 으로, ranges:: begin ( r2 ) first2 로, 그리고 ranges:: end ( r2 ) last2 로 사용하는 것과 같습니다.

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

목차

매개변수

first1, last1 - 첫 번째 요소들의 범위 를 정의하는 반복자-감시자 쌍
first2, last2 - 두 번째 요소들의 범위 를 정의하는 반복자-감시자 쌍
r1 - 요소들의 첫 번째 range
r2 - 요소들의 두 번째 range
pred - 투영된 요소들에 적용할 조건자
proj1 - 첫 번째 범위의 요소들에 적용할 투영
proj2 - 두 번째 범위의 요소들에 적용할 투영

반환값

true 를 반환합니다, 만약 범위 [ first1 , last1 ) 가 범위 [ first2 , last2 ) 의 순열(permutation)인 경우.

복잡도

최대 O(N 2 ) 번의 술어 및 각 프로젝션 적용, 또는 시퀀스가 이미 동일한 경우 정확히 N 번 적용됩니다. 여기서 N ranges:: distance ( first1, last1 ) 입니다. 그러나 만약 ranges:: distance ( first1, last1 ) ! = ranges:: distance ( first2, last2 ) 인 경우, 술어 및 프로젝션의 적용이 이루어지지 않습니다.

참고 사항

permutation 관계는 equivalence relation 입니다.

ranges::is_permutation 은 정렬, 셔플링, 분할과 같은 재배열 알고리즘의 정확성을 검증하는 테스트 등에서 사용될 수 있습니다. p 가 원본 시퀀스이고 q 가 "변형된" 시퀀스라면, ranges :: is_permutation ( p, q ) == true q p 와 "동일한" 요소들(순서가 바뀌었을 수 있음)로 구성되어 있음을 의미합니다.

가능한 구현

struct is_permutation_fn
{
    template<std::forward_iterator I1, std::sentinel_for<I1> S1,
             std::forward_iterator I2, std::sentinel_for<I2> S2,
             class Proj1 = std::identity, class Proj2 = std::identity,
             std::indirect_equivalence_relation<std::projected<I1, Proj1>,
                                                std::projected<I2, Proj2>>
                                                    Pred = ranges::equal_to>
    constexpr bool operator()(I1 first1, S1 last1, I2 first2, S2 last2,
                              Pred pred = {}, Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        // 공통 접두사 건너뛰기
        auto ret = std::ranges::mismatch(first1, last1, first2, last2,
                                         std::ref(pred), std::ref(proj1), std::ref(proj2));
        first1 = ret.in1, first2 = ret.in2;
        // 나머지 요소들을 순회하며 각 요소가 몇 번 나타나는지 계산
        // [first1, last1) 범위의 요소가 [first2, last2) 범위에 나타나는지 확인
        for (auto i {first1}; i != last1; ++i)
        {
            const auto i_proj {std::invoke(proj1, *i)};
            auto i_cmp = [&]<typename T>(T&& t)
            { 
                return std::invoke(pred, i_proj, std::forward<T>(t));
            };
            if (i != ranges::find_if(first1, i, i_cmp, proj1))
                continue; // 이 *i는 검증되었습니다
            if (const auto m {ranges::count_if(first2, last2, i_cmp, proj2)};
                m == 0 or m != ranges::count_if(i, last1, i_cmp, proj1))
                return false;
        }
        return true;
    }
    template<ranges::forward_range R1, ranges::forward_range R2,
             class Proj1 = std::identity, class Proj2 = std::identity,
             std::indirect_equivalence_relation<
                 std::projected<ranges::iterator_t<R1>, Proj1>,
                 std::projected<ranges::iterator_t<R2>, Proj2>>
                     Pred = ranges::equal_to>
    constexpr bool operator()(R1&& r1, R2&& r2, Pred pred = {},
                              Proj1 proj1 = {}, Proj2 proj2 = {}) const
    {
        return (*this)(ranges::begin(r1), ranges::end(r1),
                       ranges::begin(r2), ranges::end(r2),
                       std::move(pred), std::move(proj1), std::move(proj2));
    }
};
inline constexpr is_permutation_fn is_permutation {};

예제

#include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <ranges>
auto& operator<<(auto& os, std::ranges::forward_range auto const& v)
{
    os << "{ ";
    for (const auto& e : v)
        os << e << ' ';
    return os << "}";
}
int main()
{
    static constexpr auto r1 = {1, 2, 3, 4, 5};
    static constexpr auto r2 = {3, 5, 4, 1, 2};
    static constexpr auto r3 = {3, 5, 4, 1, 1};
    static_assert(
        std::ranges::is_permutation(r1, r1) &&
        std::ranges::is_permutation(r1, r2) &&
        std::ranges::is_permutation(r2, r1) &&
        std::ranges::is_permutation(r1.begin(), r1.end(), r2.begin(), r2.end()));
    std::cout
        << std::boolalpha
        << "is_permutation(" << r1 << ", " << r2 << "): "
        << std::ranges::is_permutation(r1, r2) << '\n'
        << "is_permutation(" << r1 << ", " << r3 << "): "
        << std::ranges::is_permutation(r1, r3) << '\n'
        << "is_permutation with custom predicate and projections: "
        << std::ranges::is_permutation(
            std::array {-14, -11, -13, -15, -12},  // 1st range
            std::array {'F', 'E', 'C', 'B', 'D'},  // 2nd range
            [](int x, int y) { return abs(x) == abs(y); }, // predicate
            [](int x) { return x + 10; },          // projection for 1st range
            [](char y) { return int(y - 'A'); })   // projection for 2nd range
        << '\n';
}

출력:

is_permutation({ 1 2 3 4 5 }, { 3 5 4 1 2 }): true
is_permutation({ 1 2 3 4 5 }, { 3 5 4 1 1 }): false
is_permutation with custom predicate and projections: true

참고 항목

원소 범위의 다음으로 큰 사전식 순열을 생성함
(알고리즘 함수 객체)
원소 범위의 다음으로 작은 사전식 순열을 생성함
(알고리즘 함수 객체)
한 시퀀스가 다른 시퀀스의 순열인지 판별함
(함수 템플릿)
원소 범위의 다음으로 큰 사전식 순열을 생성함
(함수 템플릿)
원소 범위의 다음으로 작은 사전식 순열을 생성함
(함수 템플릿)
relation 이 동치 관계를 부과함을 명시함
(컨셉)