💡 퀵 접속: cpp.kr/replace_if

replace_if

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 조건을 만족하는 요소들을 새로운 값으로 대체합니다. replace_if는 원본 범위를 직접 수정하며, 조건을 만족하는 모든 요소들을 새로운 값으로 변경합니다.

기본 사용법

#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;
    
    // 짝수를 0으로 대체
    std::replace_if(numbers.begin(), numbers.end(),
                   [](int n) { return n % 2 == 0; }, 0);
    
    std::cout << "짝수를 0으로 대체한 후: ";
    for (int n : numbers) std::cout << n << " ";
    std::cout << std::endl;
    
    return 0;
}

실행 결과:

원본 벡터: 1 2 3 4 5 6 7 8 9 10
짝수를 0으로 대체한 후: 1 0 3 0 5 0 7 0 9 0

문자열에서 사용

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

int main() {
    std::string text = "Hello, World! 123";
    
    std::cout << "원본 문자열: " << text << std::endl;
    
    // 숫자를 '#'으로 대체
    std::replace_if(text.begin(), text.end(),
                   [](char c) { return std::isdigit(c); }, '#');
    
    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 객체들을 Eve(30세)로 대체
    Person new_person("Eve", 30);
    std::replace_if(people.begin(), people.end(),
                   [](const Person& p) { return p.getAge() >= 30; },
                   new_person);
    
    std::cout << "\n30세 이상인 사람들을 Eve(30세)로 대체한 후:" << std::endl;
    for (const auto& person : people) {
        person.print();
    }
    
    return 0;
}

실행 결과:

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

30세 이상인 사람들을 Eve(30세)로 대체한 후:
Alice (20세)
Eve (30세)
Charlie (25세)
Eve (30세)
Eve (22세)

참고사항

  • replace_if는 algorithm 헤더에 정의되어 있습니다.
  • 원본 범위를 직접 수정합니다.
  • 시간 복잡도는 O(n)입니다.
  • 조건을 만족하는 모든 요소들이 새로운 값으로 대체됩니다.
  • 요소의 순서는 유지됩니다.
  • 예외 안전성을 보장합니다.
  • replace는 특정 값을 가진 요소들을 대체하는 버전입니다.
  • replace_copy_if는 원본을 수정하지 않고 결과를 다른 범위에 복사하는 버전입니다.
함수 설명
replace_if(first, last, pred, new_value) 범위 [first, last)에서 조건 pred를 만족하는 요소들을 new_value로 대체