forward_list_unique
forward_list_unique (std::forward_list::unique — 인접 중복 제거)
std::forward_list에서 연속된 중복 원소들을 제거하는 멤버 함수예요. 같은 원소들의 각 그룹에서 첫 번째만 남겨요.
출처: cppreference
본문
시그니처는 다음과 같아요.
void unique(); // (1) (since C++11) (until C++20)
size_type unique(); // (since C++20)
template< class BinaryPredicate >
void unique( BinaryPredicate p ); // (2) (since C++11) (until C++20)
template< class BinaryPredicate >
size_type unique( BinaryPredicate p ); // (since C++20)
컨테이너에서 연속된 중복 원소들을 모두 제거해요. 같은 원소들의 각 그룹에서 첫 번째 원소만 남겨요. 제거된 원소에 대한 이터레이터와 참조만 무효화돼요.
(1) 원소들을 operator==로 비교해요.
(2) 원소들을 p로 비교해요.
C++20부터는 제거된 원소의 개수를 반환해요. binary_pred가 등치 관계(equivalence relation)를 나타내지 않으면 동작이 정의되지 않아요.
복잡도
std::distance(begin(), end())에 선형(linear)이에요. 참고로 연속된 원소들만 비교하므로, 정렬되지 않은 리스트에선 비연속 중복은 제거되지 않아요.
예제
#include <forward_list>
#include <iostream>
int main()
{
std::forward_list<int> fl{1, 1, 2, 3, 3, 3, 4, 2, 2};
fl.unique(); // {1, 2, 3, 4, 2} — 연속 중복만 제거
for (int x : fl) std::cout << x << ' ';
}