💡 퀵 접속: cpp.kr/remove

remove

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 값을 가진 요소들을 제거합니다. remove는 실제로 요소를 삭제하지 않고, 제거할 요소들을 범위의 끝으로 이동시키고 새로운 끝 위치를 반환합니다. 실제 요소 삭제를 위해서는 컨테이너의 erase 멤버 함수와 함께 사용해야 합니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 2, 4, 2, 5};
    
    std::cout << "원본 벡터: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    // 값이 2인 요소들을 제거
    auto new_end = std::remove(numbers.begin(), numbers.end(), 2);
    
    // 실제로 요소들을 삭제
    numbers.erase(new_end, numbers.end());
    
    std::cout << "2를 제거한 후: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본 벡터: 1 2 3 2 4 2 5
2를 제거한 후: 1 3 4 5

문자열에서 사용

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string text = "Hello, World!";
    
    std::cout << "원본 문자열: " << text << std::endl;
    
    // 공백 문자 제거
    auto new_end = std::remove(text.begin(), text.end(), ' ');
    
    // 실제로 문자들을 삭제
    text.erase(new_end, text.end());
    
    std::cout << "공백을 제거한 후: " << text << 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> people = {
        Person("Alice", 20),
        Person("Bob", 30),
        Person("Charlie", 20),
        Person("David", 30),
        Person("Eve", 20)
    };
    
    std::cout << "원본 목록:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    // 20세인 Person 객체들을 제거
    Person target("", 20);
    auto new_end = std::remove(people.begin(), people.end(), target);
    
    // 실제로 요소들을 삭제
    people.erase(new_end, people.end());
    
    std::cout << "\n20세인 사람들을 제거한 후:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    return 0;
}

실행 결과:

원본 목록:
Alice (20세)
Bob (30세)
Charlie (20세)
David (30세)
Eve (20세)

20세인 사람들을 제거한 후:
Bob (30세)
David (30세)

참고사항

  • remove는 algorithm 헤더에 정의되어 있습니다.
  • 실제로 요소를 삭제하지 않고, 제거할 요소들을 범위의 끝으로 이동시킵니다.
  • 시간 복잡도는 O(n)입니다.
  • 요소의 상대적 순서는 유지됩니다.
  • 실제 요소 삭제를 위해서는 컨테이너의 erase 멤버 함수와 함께 사용해야 합니다.
  • remove_if는 조건을 만족하는 요소들을 제거하는 버전입니다.
  • remove_copy는 원본을 수정하지 않고 결과를 다른 범위에 복사하는 버전입니다.
함수 설명
remove(first, last, value) 범위 [first, last)에서 value와 같은 요소들을 제거하고 새로운 끝 위치를 반환