algorithm_unique

algorithm_unique (연속 중복 제거)

std::unique는 대상 범위에서 연속된 동등한 요소 그룹의 첫 번째 요소만 남기고 나머지를 "제거"해요. 새 범위의 끝 반복자를 돌려줘요.

출처: cppreference

본문

std::unique는 대상 범위 [first, last)에서 연속된 동등한 요소 그룹마다 첫 번째 요소만 남겨요. 실제 삭제가 아니라 요소들이 앞쪽으로 옮겨지는 방식이에요. <algorithm> 헤더에 정의되어 있어요.

template< class ForwardIt >
ForwardIt unique( ForwardIt first, ForwardIt last );

template< class ForwardIt, class BinaryPred >
ForwardIt unique( ForwardIt first, ForwardIt last, BinaryPred p );
  • 1번 오버로드 — 요소를 operator==로 비교해요.
  • 2번 오버로드 — 요소를 이진 술어 p로 비교해요.
  • 병렬 실행 정책을 받는 오버로드도 있어요.

반환값 (Return value)

제거 후 새 범위의 끝(past-the-end)을 가리키는 반복자예요.

복잡도 (Complexity)

Nstd::distance(first, last)라고 하면 for non-WriteEnabler N의 경우 N - 1번의 p 적용(또는 비교)이 필요해요.

예제 (Example)

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

int main()
{
    std::vector<int> v{1, 1, 2, 3, 3, 3, 4, 5, 5};
    auto it = std::unique(v.begin(), v.end());
    v.erase(it, v.end());
    for (int x : v) std::cout << x << ' ';
    std::cout << '\n';
}

출력:

1 2 3 4 5

더 알아보기 (Learn more)

cppreference