💡 퀵 접속: cpp.kr/unique_copy
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 연속된 중복 요소들을 제거하고 그 결과를 다른 범위에 복사합니다. unique_copy는 원본 범위를 수정하지 않으며, 중복이 제거된 결과를 새로운 범위에 저장합니다. 이 함수는 정렬된 범위에서 사용하는 것이 가장 효과적입니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 1, 2, 2, 2, 3, 3, 4, 4, 4};
std::vector<int> result;
std::cout << "원본 벡터: ";
for (int x : v) std::cout << x << " ";
std::cout << std::endl;
// 중복 요소 제거하여 result에 복사
std::unique_copy(v.begin(), v.end(), std::back_inserter(result));
std::cout << "중복 제거 후: ";
for (int x : result) std::cout << x << " ";
std::cout << std::endl;
return 0;
}
실행 결과:
원본 벡터: 1 1 2 2 2 3 3 4 4 4 중복 제거 후: 1 2 3 4
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string s = "Hello World!!";
std::string result;
std::cout << "원본 문자열: " << s << std::endl;
// 연속된 공백 제거하여 result에 복사
std::unique_copy(s.begin(), s.end(), std::back_inserter(result),
[](char a, char b) { return a == ' ' && b == ' '; });
std::cout << "공백 제거 후: " << result << std::endl;
return 0;
}
실행 결과:
원본 문자열: Hello World!! 공백 제거 후: Hello World!!
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class Person {
std::string name;
int age;
public:
Person(const std::string& n, int a) : name(n), age(a) {}
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
void print() const {
std::cout << name << " (" << age << "세)" << std::endl;
}
};
int main() {
std::vector<Person> v = {
Person("Alice", 20),
Person("Alice", 20),
Person("Bob", 30),
Person("Bob", 30),
Person("Charlie", 40)
};
std::vector<Person> result;
std::cout << "원본 벡터:" << std::endl;
for (const auto& p : v) p.print();
// 중복 요소 제거하여 result에 복사
std::unique_copy(v.begin(), v.end(), std::back_inserter(result));
std::cout << "\n중복 제거 후:" << std::endl;
for (const auto& p : result) p.print();
return 0;
}
실행 결과:
원본 벡터: Alice (20세) Alice (20세) Bob (30세) Bob (30세) Charlie (40세) 중복 제거 후: Alice (20세) Bob (30세) Charlie (40세)
| 함수 | 설명 |
|---|---|
| unique_copy(first, last, result) | [first, last) 범위에서 연속된 중복 요소들을 제거하고 결과를 result부터 저장 |
| unique_copy(first, last, result, pred) | [first, last) 범위에서 pred를 만족하는 연속된 중복 요소들을 제거하고 결과를 result부터 저장 |