💡 퀵 접속: cpp.kr/remove_if
C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 조건을 만족하는 요소들을 제거합니다. remove_if는 실제로 요소를 삭제하지 않고, 제거할 요소들을 범위의 끝으로 이동시키고 새로운 끝 위치를 반환합니다. 실제 요소 삭제를 위해서는 컨테이너의 erase 멤버 함수와 함께 사용해야 합니다.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::cout << "원본 벡터: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
// 짝수를 제거
auto new_end = std::remove_if(numbers.begin(), numbers.end(),
[](int n) { return n % 2 == 0; });
// 실제로 요소들을 삭제
numbers.erase(new_end, numbers.end());
std::cout << "짝수를 제거한 후: ";
for (int n : numbers) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
실행 결과:
원본 벡터: 1 2 3 4 5 6 7 8 9 10 짝수를 제거한 후: 1 3 5 7 9
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
std::string text = "Hello, World! 123";
std::cout << "원본 문자열: " << text << std::endl;
// 숫자를 제거
auto new_end = std::remove_if(text.begin(), text.end(),
[](char c) { return std::isdigit(c); });
// 실제로 문자들을 삭제
text.erase(new_end, text.end());
std::cout << "숫자를 제거한 후: " << text << std::endl;
return 0;
}
실행 결과:
원본 문자열: Hello, World! 123 숫자를 제거한 후: 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) {}
void print() const {
std::cout << name << " (" << age << "세)" << std::endl;
}
int getAge() const { return age; }
};
int main() {
std::vector<Person> people = {
Person("Alice", 20),
Person("Bob", 30),
Person("Charlie", 25),
Person("David", 35),
Person("Eve", 22)
};
std::cout << "원본 목록:" << std::endl;
for (const auto& person : people) {
person.print();
}
// 30세 이상인 Person 객체들을 제거
auto new_end = std::remove_if(people.begin(), people.end(),
[](const Person& p) { return p.getAge() >= 30; });
// 실제로 요소들을 삭제
people.erase(new_end, people.end());
std::cout << "\n30세 이상인 사람들을 제거한 후:" << std::endl;
for (const auto& person : people) {
person.print();
}
return 0;
}
실행 결과:
원본 목록: Alice (20세) Bob (30세) Charlie (25세) David (35세) Eve (22세) 30세 이상인 사람들을 제거한 후: Alice (20세) Charlie (25세) Eve (22세)
| 함수 | 설명 |
|---|---|
| remove_if(first, last, pred) | 범위 [first, last)에서 조건 pred를 만족하는 요소들을 제거하고 새로운 끝 위치를 반환 |