template<class ForwardIt>
ForwardIt unique(ForwardIt first, ForwardIt last); // constexpr since C++20
template<class ForwardIt, class BinaryPred>
ForwardIt unique(ForwardIt first, ForwardIt last, BinaryPred p); // constexpr since C++20
C++17 ~
template<class ExecutionPolicy, class ForwardIt>
ForwardIt unique(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last);
template<class ExecutionPolicy, class ForwardIt, class BinaryPred>
ForwardIt unique(ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, BinaryPred p);
: 주어진 범위 내의 요소들 중에서 연속된 중복 요소를 범위 뒤쪽으로 치운 후 새로운 끝을 가리키는 순방향 반복자를 반환합니다.
실제 크기를 줄이기 위해서는 erase를 함께 사용해주면 좋습니다.
실행 정책은 std::execution 헤더에 포함되어있습니다.
- execution::seq : 순차 실행 (기본 값)
- execution::par : 병렬 실행 (멀티코어 시스템에서 작업이 병렬로 수행됩니다.)
- execution::par_unseq : 병렬 및 비순차 실행 (예를 들어, 5개의 요소가 있을 때 2번과 4번 요소가 바뀐 후 1번과 5번 요소가 바뀔 수 있습니다.)
<example>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
vector<int> vec = { 1, 1, 2, 2, 2, 3, 4, 4 };
auto newEnd = unique(vec.begin(), vec.end());
for (auto it = vec.begin(); it != newEnd; ++it) {
cout << *it << ' ';
}
cout << endl;
cout << "size before erase: " << vec.size() << endl;
vec.erase(newEnd, vec.end()); // 실제 크기 줄이기
cout << "size after erase: " << vec.size() << endl;
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << ' ';
}
return 0;
}
결과값
<p example>
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
int main() {
vector<int> vec = { -1, 1, 2, 2, 2, -3, 4, -4 };
auto newEnd = unique(vec.begin(), vec.end(),
[](const int &a, const int &b) {return abs(a) == abs(b); }); // 절대값으로 중복의 기준을 정의
for (auto it = vec.begin(); it != newEnd; ++it) {
cout << *it << ' ';
}
return 0;
}
결과값
