Namespaces
Variants

std::set_difference

cppreference.net에서
 
 
알고리즘 라이브러리
제약된 알고리즘 및 범위에 대한 알고리즘 (C++20)
제약된 알고리즘, 예: ranges::copy, ranges::sort, ...
정렬 및 관련 연산
분할 연산
(C++11)    

정렬 연산
이진 검색 연산
(분할된 범위에서)
집합 연산 (정렬된 범위에서)
병합 연산 (정렬된 범위에서)
힙 연산
최소/최대 연산
(C++11)
(C++17)
사전식 비교 연산
순열 연산


 
다음 헤더에 정의됨 <algorithm>
template< class InputIt1, class InputIt2, class OutputIt >
OutputIt set_difference( InputIt1 first1, InputIt1 last1,
                         InputIt2 first2, InputIt2 last2,
                         OutputIt d_first );
(1) (C++20부터 constexpr)
template< class ExecutionPolicy,
          class ForwardIt1, class ForwardIt2, class ForwardIt3 >
ForwardIt3 set_difference( ExecutionPolicy&& policy,
                           ForwardIt1 first1, ForwardIt1 last1,
                           ForwardIt2 first2, ForwardIt2 last2,
                           ForwardIt3 d_first );
(2) (C++17부터)
template< class InputIt1, class InputIt2,
          class OutputIt, class Compare >
OutputIt set_difference( InputIt1 first1, InputIt1 last1,
                         InputIt2 first2, InputIt2 last2,
                         OutputIt d_first, Compare comp );
(3) (C++20부터 constexpr)
template< class ExecutionPolicy,
          class ForwardIt1, class ForwardIt2,
          class ForwardIt3, class Compare >
ForwardIt3 set_difference( ExecutionPolicy&& policy,
                           ForwardIt1 first1, ForwardIt1 last1,
                           ForwardIt2 first2, ForwardIt2 last2,
                           ForwardIt3 d_first, Compare comp );
(4) (C++17부터)

정렬된 범위 [first1, last1)에서 정렬된 범위 [first2, last2)에 없는 요소들을 d_first에서 시작하는 범위로 복사합니다. 출력 범위도 정렬됩니다.

만약 [first1, last1)에 서로 동등한 m개의 요소가 포함되어 있고 [first2, last2)에 그들과 동등한 n개의 요소가 포함되어 있다면, 최종 std::max(m - n, 0)개의 요소들이 순서를 유지하며 [first1, last1)에서 출력 범위로 복사됩니다.

1) [first1, last1) 또는 [first2, last2)이 정렬되지 않은 operator<(C++20까지)std::less{}(C++20부터)에 대해 동작은 정의되지 않습니다.
3) [first1, last1) 또는 [first2, last2)이 comp에 대해 정렬되지 않은 경우, 동작은 정의되지 않습니다.
2,4) (1,3)과 동일하지만, policy에 따라 실행됩니다.
이러한 오버로드는 다음 표현식의 값이 true인 경우에만 오버로드 해결에 참여합니다:

std::is_execution_policy_v<std::decay_t<ExecutionPolicy>>

(C++20까지)

std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>

(C++20부터)

출력 범위가 [first1, last1) 또는 [first2, last2)과 겹치는 경우, 동작은 정의되지 않습니다.

매개변수

first1, last1 - 검사할 첫 번째 입력 정렬된 범위 를 정의하는 반복자 쌍
first2, last2 - 검색할 두 번째 입력 정렬된 범위 를 정의하는 반복자 쌍
d_first - 출력 범위의 시작점
policy - 사용할 실행 정책
comp - 비교 함수 객체 (즉, Compare 요구 사항을 만족하는 객체)로, 첫 번째 인수가 두 번째 인수보다 작은 경우 (즉, 순서상 앞서는 경우 ) ​ true 를 반환함.

비교 함수의 시그니처는 다음과 동일해야 함:

bool cmp ( const Type1 & a, const Type2 & b ) ;

시그니처에 const & 가 필요하지는 않지만, 함수는 전달된 객체를 수정해서는 안 되며, 값 범주 에 관계없이 (가능하면 const인) Type1 및 Type2 타입의 모든 값을 수용할 수 있어야 함 (따라서 Type1& 는 허용되지 않으며, Type1 의 이동이 복사와 동등하지 않는 한 Type1 도 허용되지 않음 (C++11부터) ).
Type1 및 Type2 타입은 InputIt1 및 InputIt2 타입의 객체가 역참조된 후 Type1 과 Type2 양쪽으로 암시적으로 변환될 수 있어야 함. ​

타입 요구 사항
-
InputIt1, InputIt2 는 LegacyInputIterator 요구 사항을 충족해야 함.
-
OutputIt 는 LegacyOutputIterator 요구 사항을 충족해야 함.
-
ForwardIt1, ForwardIt2, ForwardIt3 는 LegacyForwardIterator 요구 사항을 충족해야 함.
-
Compare 는 Compare 요구 사항을 충족해야 함.

반환값

구성된 범위의 끝을 지난 반복자.

복잡도

N 1 를 std:: distance ( first1, last1 ) 로, N 2 를 std:: distance ( first2, last2 ) 로 정의할 때:

1,2) 최대 2⋅(N 1 +N 2 )-1 번의 비교를 사용하며, operator < (C++20까지) std:: less { } (C++20부터) 를 사용합니다.
3,4) 최대 2⋅(N 1 +N 2 )-1 번의 비교 함수 comp 적용.

예외

ExecutionPolicy 라는 템플릿 매개변수를 사용하는 오버로드는 다음과 같이 오류를 보고합니다:

  • 알고리즘의 일부로 호출된 함수 실행 중 예외가 발생하고 ExecutionPolicy 가 표준 정책 중 하나인 경우, std::terminate 가 호출됩니다. 다른 ExecutionPolicy 의 경우 동작은 구현에 따라 정의됩니다.
  • 알고리즘이 메모리 할당에 실패할 경우, std::bad_alloc 이 throw됩니다.

가능한 구현

set_difference (1)
template<class InputIt1, class InputIt2, class OutputIt>
OutputIt set_difference(InputIt1 first1, InputIt1 last1,
                        InputIt2 first2, InputIt2 last2, OutputIt d_first)
{
    while (first1 != last1)
    {
        if (first2 == last2)
            return std::copy(first1, last1, d_first);
        if (*first1 < *first2)
            *d_first++ = *first1++;
        else
        {
            if (! (*first2 < *first1))
                ++first1;
            ++first2;
        }
    }
    return d_first;
}
set_difference (3)
template<class InputIt1, class InputIt2, class OutputIt, class Compare>
OutputIt set_difference(InputIt1 first1, InputIt1 last1,
                        InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp)
{
    while (first1 != last1)
    {
        if (first2 == last2)
            return std::copy(first1, last1, d_first);
        if (comp(*first1, *first2))
            *d_first++ = *first1++;
        else
        {
            if (!comp(*first2, *first1))
                ++first1;
            ++first2;
        }
    }
    return d_first;
}

예제

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v)
{
    os << '{';
    for (auto n{v.size()}; const auto& e : v)
        os << e << (--n ? ", " : "");
    return os << '}';
}
struct Order // 매우 흥미로운 데이터를 가진 구조체
{
    int order_id{};
    friend std::ostream& operator<<(std::ostream& os, const Order& ord)
    {
        return os << ord.order_id;
    }
};
int main()
{
    const std::vector<int> v1{1, 2, 5, 5, 5, 9};
    const std::vector<int> v2{2, 5, 7};
    std::vector<int> diff;
    std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(),
                        std::inserter(diff, diff.begin()));
    std::cout << v1 << " ∖ " << v2 << " == " << diff << "\n\n";
    // 이전 상태와 새 상태 사이에서 어떤 주문들이 "제거"되었는지 알고 싶습니다:
    std::vector<Order> old_orders{{1}, {2}, {5}, {9}};
    std::vector<Order> new_orders{{2}, {5}, {7}};
    std::vector<Order> cut_orders;
    std::set_difference(old_orders.begin(), old_orders.end(),
                        new_orders.begin(), new_orders.end(),
                        std::back_inserter(cut_orders),
                        [](auto& a, auto& b) { return a.order_id < b.order_id; });
    std::cout << "old orders: " << old_orders << '\n'
              << "new orders: " << new_orders << '\n'
              << "cut orders: " << cut_orders << '\n';
}

출력:

{1, 2, 5, 5, 5, 9} ∖ {2, 5, 7} == {1, 5, 5, 9}
old orders: {1, 2, 5, 9}
new orders: {2, 5, 7}
cut orders: {1, 9}

결함 보고서

다음의 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 291 C++98 입력 범위에서 동등한 요소를 어떻게 처리할지 명시되지 않았음 명시됨

참고

한 시퀀스가 다른 시퀀스의 부분 시퀀스인지 결정합니다
(함수 템플릿 & 알고리즘 함수 객체)
두 집합의 대칭 차집합을 계산합니다
(함수 템플릿 & 알고리즘 함수 객체)
두 집합의 차집합을 계산합니다
(알고리즘 함수 객체)