algorithm_unique_copy
algorithm_unique_copy (중복 제거하며 복사)
std::unique_copy는 소스 범위에서 연속된 동등한 요소 그룹의 첫 번째 요소만 목적지 범위로 복사해요. 원본을 변경하지 않고 중복을 제거한 결과를 얻어요.
출처: cppreference
본문
std::unique_copy는 소스 범위 [first, last)의 요소들을 d_first에서 시작하는 목적지 범위로 복사해요. 연속된 동등한 요소 그룹마다 첫 번째 요소만 복사돼요. <algorithm> 헤더에 정의되어 있어요.
template< class InputIt, class OutputIt >
OutputIt unique_copy( InputIt first, InputIt last, OutputIt d_first );
template< class InputIt, class OutputIt, class BinaryPred >
OutputIt unique_copy( InputIt first, InputIt last,
OutputIt d_first, BinaryPred p );
- 1번 오버로드 — 요소를
operator==로 비교해요. - 2번 오버로드 — 요소를 이진 술어
p로 비교해요. - 병렬 실행 정책을 받는 오버로드도 있어요.
반환값 (Return value)
복사된 마지막 요소 다음의 반복자예요.
복잡도 (Complexity)
N을 std::distance(first, last)라고 하면 N - 1번의 p 적용(또는 비교)이 필요해요.
예제 (Example)
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> v{1, 1, 2, 3, 3, 3, 4, 5, 5};
std::vector<int> out;
std::unique_copy(v.begin(), v.end(), std::back_inserter(out));
for (int x : out) std::cout << x << ' ';
std::cout << '\n';
}
출력:
1 2 3 4 5