Namespaces
Variants

std:: unique

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
헤더 파일에 정의됨 <algorithm>
template < class ForwardIt >
ForwardIt unique ( ForwardIt first, ForwardIt last ) ;
(1) (constexpr since C++20)
template < class ExecutionPolicy, class ForwardIt >

ForwardIt unique ( ExecutionPolicy && policy,

ForwardIt first, ForwardIt last ) ;
(2) (since C++17)
template < class ForwardIt, class BinaryPred >
ForwardIt unique ( ForwardIt first, ForwardIt last, BinaryPred p ) ;
(3) (constexpr since C++20)
template < class ExecutionPolicy,

class ForwardIt, class BinaryPred >
ForwardIt unique ( ExecutionPolicy && policy,

ForwardIt first, ForwardIt last, BinaryPred p ) ;
(4) (since C++17)

동등한 요소들의 연속된 그룹에서 첫 번째 요소를 제외한 모든 요소를 범위 [ first , last ) 에서 제거하고, 새로운 범위 끝을 가리키는 past-the-end 반복자를 반환합니다.

1) 요소들은 operator == 를 사용하여 비교됩니다.
만약 operator == 동치 관계 를 설정하지 않으면, 동작은 정의되지 않습니다.
3) 요소들은 주어진 이항 조건자 p 를 사용하여 비교됩니다.
만약 p 가 동치 관계를 설정하지 않으면, 동작은 정의되지 않습니다.
2,4) (1,3) 와 동일하지만, policy 에 따라 실행됩니다.
다음 모든 조건이 만족될 때만 이 오버로드들이 오버로드 해결에 참여합니다:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> true 인 경우.

(C++20 이전)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> true 인 경우.

(C++20 이후)

목차

설명

제거는 범위 내 요소들을 이동시켜 제거되지 않을 요소들이 범위의 시작 부분에 나타나도록 하는 방식으로 수행됩니다.

  • 시프팅은 copy assignment (until C++11) move assignment (since C++11) 에 의해 수행됩니다.
  • 제거 작업은 안정적입니다: 제거되지 않는 요소들의 상대적 순서는 유지됩니다.
  • [ first , last ) 의 기본 시퀀스는 제거 작업에 의해 단축되지 않습니다. 반환된 반복자로 result 가 주어집니다:
  • [ result , last ) 범위 내의 모든 반복자는 여전히 역참조 가능 합니다.
  • [ result , last ) 범위의 각 요소는 유효하지만 지정되지 않은 상태를 가지며, 이는 이동 할당이 원래 해당 범위에 있던 요소들로부터 이동하여 요소들을 제거할 수 있기 때문입니다.
(C++11부터)

매개변수

first, last - 처리할 요소들의 범위 를 정의하는 반복자 쌍
policy - 사용할 실행 정책
p - 요소들이 동등하게 처리되어야 할 경우 ​ true 를 반환하는 이항 predicate.

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

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

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

타입 요구사항
-
ForwardIt LegacyForwardIterator 요구사항을 충족해야 합니다.
-
ForwardIt 의 역참조 타입은 MoveAssignable 요구사항을 충족해야 합니다.

반환값

범위의 새로운 끝을 가리키는 ForwardIt 입니다.

복잡도

주어진 N std:: distance ( first, last ) 인 경우:

1,2) 정확히 max(0,N-1) 번의 비교를 operator == 를 사용하여 수행합니다.
3,4) 정확히 max(0,N-1) 번의 predicate p 적용.

예외

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

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

가능한 구현

다음 구현들도 참조하십시오: libstdc++ , libc++ , 그리고 MSVC STL .

unique (1)
template<class ForwardIt>
ForwardIt unique(ForwardIt first, ForwardIt last)
{
    if (first == last)
        return last;
    ForwardIt result = first;
    while (++first != last)
        if (!(*result == *first) && ++result != first)
            *result = std::move(*first);
    return ++result;
}
unique (3)
template<class ForwardIt, class BinaryPredicate>
ForwardIt unique(ForwardIt first, ForwardIt last, BinaryPredicate p)
{
    if (first == last)
        return last;
    ForwardIt result = first;
    while (++first != last)
        if (!p(*result, *first) && ++result != first)
            *result = std::move(*first);
    return ++result;
}

참고 사항

unique 에 대한 호출은 일반적으로 컨테이너의 erase 멤버 함수 호출이 뒤따라, 실제로 컨테이너에서 요소들을 제거합니다.

예제

#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
    // 여러 중복 요소를 포함하는 벡터
    std::vector<int> v{1, 2, 1, 1, 3, 3, 3, 4, 5, 4};
    auto print = [&](int id)
    {
        std::cout << "@" << id << ": ";
        for (int i : v)
            std::cout << i << ' ';
        std::cout << '\n';
    };
    print(1);
    // 연속된(인접한) 중복 제거
    auto last = std::unique(v.begin(), v.end());
    // v는 이제 {1 2 1 3 4 5 4 x x x}를 보유하며, 여기서 'x'는 불확정 값
    v.erase(last, v.end());
    print(2);
    // 모든 중복을 제거하기 위한 정렬 후 unique 적용
    std::sort(v.begin(), v.end()); // {1 1 2 3 4 4 5}
    print(3);
    last = std::unique(v.begin(), v.end());
    // v는 이제 {1 2 3 4 5 x x}를 보유하며, 여기서 'x'는 불확정 값
    v.erase(last, v.end());
    print(4);
}

출력:

@1: 1 2 1 1 3 3 3 4 5 4
@2: 1 2 1 3 4 5 4
@3: 1 1 2 3 4 4 5
@4: 1 2 3 4 5

결함 보고서

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

DR 적용 대상 게시된 동작 올바른 동작
LWG 202 C++98 요소들이 비동치 관계를 사용하여
비교될 경우 동작이 불명확했음
이 경우 동작은
정의되지 않음

참고 항목

서로 같은(또는 주어진 조건자를 만족하는) 첫 두 개의 인접 항목을 찾음
(함수 템플릿)
연속된 중복 요소가 없는 일부 범위의 복사본을 생성함
(함수 템플릿)
특정 기준을 만족하는 요소들을 제거함
(함수 템플릿)
연속된 중복 요소들을 제거함
( std::list<T,Allocator> 의 public 멤버 함수)
연속된 중복 요소들을 제거함
( std::forward_list<T,Allocator> 의 public 멤버 함수)
범위 내에서 연속된 중복 요소들을 제거함
(알고리즘 함수 객체)