💡 퀵 접속: cpp.kr/unique_copy

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는 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위를 수정하지 않습니다.
  • 시간 복잡도는 O(n)입니다.
  • 연속된 중복 요소만 제거합니다.
  • 정렬된 범위에서 사용하는 것이 가장 효과적입니다.
  • 결과를 저장할 범위는 충분한 크기여야 합니다.
  • std::back_inserter를 사용하여 결과를 동적으로 저장할 수 있습니다.
  • 사용자 정의 타입에 대해서는 operator==가 정의되어 있어야 합니다.
  • 커스텀 비교 함수를 사용할 수 있습니다.
  • unique는 원본을 직접 수정하는 버전입니다.
함수 설명
unique_copy(first, last, result) [first, last) 범위에서 연속된 중복 요소들을 제거하고 결과를 result부터 저장
unique_copy(first, last, result, pred) [first, last) 범위에서 pred를 만족하는 연속된 중복 요소들을 제거하고 결과를 result부터 저장