💡 퀵 접속: cpp.kr/is_permutation

is_permutation

C++ 표준 라이브러리의 알고리즘으로, 두 범위가 서로 순열 관계인지 확인합니다. 즉, 두 번째 범위가 첫 번째 범위의 요소들을 재배열한 것인지 검사합니다.

기본 사용법

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

int main() {
    std::vector<int> v1 = {1, 2, 3, 4, 5};
    std::vector<int> v2 = {3, 5, 1, 4, 2};
    std::vector<int> v3 = {1, 2, 3, 4, 6};
    
    // v1과 v2가 순열 관계인지 확인
    bool is_perm1 = std::is_permutation(v1.begin(), v1.end(), v2.begin());
    std::cout << "v1과 v2는 순열 관계" << (is_perm1 ? "입니다." : "가 아닙니다.") << std::endl;
    
    // v1과 v3가 순열 관계인지 확인
    bool is_perm2 = std::is_permutation(v1.begin(), v1.end(), v3.begin());
    std::cout << "v1과 v3는 순열 관계" << (is_perm2 ? "입니다." : "가 아닙니다.") << std::endl;
    
    return 0;
}

실행 결과:

v1과 v2는 순열 관계입니다.
v1과 v3는 순열 관계가 아닙니다.

커스텀 비교 함수 사용

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

int main() {
    std::vector<int> v1 = {5, 4, 3, 2, 1};
    std::vector<int> v2 = {1, 3, 5, 2, 4};
    
    // 절대값이 같은 경우를 같은 것으로 간주
    auto abs_compare = [](int a, int b) {
        return std::abs(a) == std::abs(b);
    };
    
    bool is_perm = std::is_permutation(v1.begin(), v1.end(), v2.begin(), abs_compare);
    std::cout << "절대값 기준으로 순열 관계" << (is_perm ? "입니다." : "가 아닙니다.") << std::endl;
    
    return 0;
}

실행 결과:

절대값 기준으로 순열 관계입니다.

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Person {
    std::string name;
    int age;
    
    bool operator==(const Person& other) const {
        return age == other.age;
    }
};

int main() {
    std::vector<Person> group1 = {
        {"Alice", 20},
        {"Bob", 25},
        {"Charlie", 30}
    };
    
    std::vector<Person> group2 = {
        {"David", 25},
        {"Eve", 30},
        {"Frank", 20}
    };
    
    // 나이가 같은 경우를 같은 것으로 간주
    bool is_perm = std::is_permutation(group1.begin(), group1.end(), group2.begin());
    std::cout << "나이 기준으로 순열 관계" << (is_perm ? "입니다." : "가 아닙니다.") << std::endl;
    
    return 0;
}

실행 결과:

나이 기준으로 순열 관계입니다.

참고사항

  • is_permutation은 algorithm 헤더에 정의되어 있습니다.
  • 기본적으로 == 연산자를 사용하여 비교합니다.
  • 커스텀 비교 함수를 제공할 수 있습니다.
  • 시간 복잡도는 O(n²)입니다 (n은 범위의 크기).
  • 두 번째 범위의 크기가 첫 번째 범위보다 작으면 안 됩니다.
  • 두 범위의 요소 개수가 다르면 false를 반환합니다.
함수 설명
is_permutation(first1, last1, first2) 기본 비교 연산자를 사용하여 두 범위가 순열 관계인지 확인
is_permutation(first1, last1, first2, pred) 커스텀 비교 함수를 사용하여 두 범위가 순열 관계인지 확인