본문으로 건너뛰기
Previous
Next
C++ Algorithm Replace | '치환 알고리즘' 가이드

C++ Algorithm Replace | '치환 알고리즘' 가이드

C++ Algorithm Replace | '치환 알고리즘' 가이드

이 글의 핵심

C++ replace, replace_if, replace_copy로 범위 치환. 원본 수정과 복사본 생성의 차이·조건 치환 실무 예를 다룹니다.

들어가며

C++ STL의 replace 알고리즘은 컨테이너의 요소를 효율적으로 치환할 수 있게 해줍니다. 값 기반 치환과 조건 기반 치환을 모두 지원합니다.


코딩 테스트 준비하며 깨달은 것

알고리즘 문제를 풀다 보면 “이게 실무에 무슨 도움이 될까?” 하는 의문이 들 때가 있습니다. 저도 그랬습니다. 하지만 실제 프로젝트에서 성능 문제에 부딪히면, 알고리즘 지식이 얼마나 중요한지 깨닫게 됩니다. 예를 들어, 사용자 검색 기능이 느려서 고민하다가 해시 테이블을 적용하니 응답 시간이 10초에서 0.1초로 줄어든 경험이 있습니다.

코딩 테스트는 단순히 취업을 위한 관문이 아니라, 문제 해결 능력을 키우는 훈련장입니다. 처음엔 브루트 포스로 풀다가, 시간 복잡도를 개선하는 과정에서 “아, 이렇게 생각하면 되는구나” 하는 깨달음을 얻을 때의 쾌감은 말로 표현하기 어렵습니다. 이 글에서는 단순히 정답 코드만 제시하는 게 아니라, 문제를 어떻게 접근하고 최적화하는지 사고 과정을 함께 공유하겠습니다.

1. std::replace

기본 사용

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

int main() {
    std::vector<int> v = {1, 2, 3, 2, 4, 2, 5};
    
    std::cout << "원본: ";
    for (int x : v) {
        std::cout << x << " ";  // 1 2 3 2 4 2 5
    }
    std::cout << std::endl;
    
    // 2를 9로 치환
    std::replace(v.begin(), v.end(), 2, 9);
    
    std::cout << "치환 후: ";
    for (int x : v) {
        std::cout << x << " ";  // 1 9 3 9 4 9 5
    }
    std::cout << std::endl;
}

문자열 치환

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

int main() {
    std::string text = "Hello World";
    
    // 공백을 밑줄로 치환
    std::replace(text.begin(), text.end(), ' ', '_');
    std::cout << text << std::endl;  // Hello_World
    
    // 특정 문자 치환
    std::string code = "int x = 10;";
    std::replace(code.begin(), code.end(), ' ', '\t');
    std::cout << code << std::endl;  // int	x	=	10;
}

함수 시그니처:

template<class ForwardIt, class T>
void replace(ForwardIt first, ForwardIt last,
             const T& old_value, const T& new_value);

핵심 개념:

  • 원본 수정: 컨테이너를 직접 수정
  • 모든 일치: 일치하는 모든 요소 치환
  • 시간 복잡도: O(n)

2. std::replace_if

조건 기반 치환

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 짝수를 0으로 치환
    std::replace_if(v.begin(), v.end(),
         { return x % 2 == 0; }, 0);
    
    for (int x : v) {
        std::cout << x << " ";  // 1 0 3 0 5 0 7 0 9 0
    }
    std::cout << std::endl;
}

복잡한 조건

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

int main() {
    std::vector<int> scores = {45, 67, 89, 34, 92, 78, 56};
    
    // 60점 미만을 0으로
    std::replace_if(scores.begin(), scores.end(),
         { return score < 60; }, 0);
    
    std::cout << "점수: ";
    for (int score : scores) {
        std::cout << score << " ";  // 0 67 89 0 92 78 0
    }
    std::cout << std::endl;
}

3. std::replace_copy

원본 유지하며 치환

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

int main() {
    std::vector<int> src = {1, 2, 3, 2, 4, 2, 5};
    std::vector<int> dst;
    
    // 복사하며 치환 (원본 유지)
    std::replace_copy(src.begin(), src.end(), 
                      std::back_inserter(dst), 2, 9);
    
    std::cout << "원본: ";
    for (int x : src) {
        std::cout << x << " ";  // 1 2 3 2 4 2 5 (변경 없음)
    }
    std::cout << std::endl;
    
    std::cout << "복사본: ";
    for (int x : dst) {
        std::cout << x << " ";  // 1 9 3 9 4 9 5
    }
    std::cout << std::endl;
}

std::replace_copy_if

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

int main() {
    std::vector<int> src = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    std::vector<int> dst;
    
    // 짝수를 0으로 치환하며 복사
    std::replace_copy_if(src.begin(), src.end(),
                         std::back_inserter(dst),
                          { return x % 2 == 0; }, 0);
    
    std::cout << "원본: ";
    for (int x : src) {
        std::cout << x << " ";  // 1 2 3 4 5 6 7 8 9 10
    }
    std::cout << std::endl;
    
    std::cout << "복사본: ";
    for (int x : dst) {
        std::cout << x << " ";  // 1 0 3 0 5 0 7 0 9 0
    }
    std::cout << std::endl;
}

4. 실전 예제

예제 1: 데이터 정제

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

int main() {
    // 센서 데이터 (오류 값 -1 포함)
    std::vector<int> sensorData = {23, -1, 25, 24, -1, 26, 23, -1};
    
    // 오류 값을 평균값으로 치환
    int validSum = 0;
    int validCount = 0;
    
    for (int value : sensorData) {
        if (value != -1) {
            validSum += value;
            validCount++;
        }
    }
    
    int average = validSum / validCount;
    
    std::replace(sensorData.begin(), sensorData.end(), -1, average);
    
    std::cout << "정제된 데이터: ";
    for (int value : sensorData) {
        std::cout << value << " ";  // 23 24 25 24 24 26 23 24
    }
    std::cout << std::endl;
}

예제 2: 텍스트 처리

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

int main() {
    std::string text = "Hello, World! How are you?";
    
    // 구두점을 공백으로
    std::replace_if(text.begin(), text.end(),
         { return c == ',' || c == '!' || c == '?'; }, ' ');
    
    std::cout << text << std::endl;
    // Hello  World  How are you 
    
    // 연속된 공백 제거는 unique 사용
}

예제 3: 범위 치환

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

int main() {
    std::vector<int> grades = {95, 45, 78, 34, 89, 67, 23, 91};
    
    // 60점 미만을 60점으로 상향 (최소 점수 보장)
    std::replace_if(grades.begin(), grades.end(),
         { return grade < 60; }, 60);
    
    std::cout << "조정된 점수: ";
    for (int grade : grades) {
        std::cout << grade << " ";  // 95 60 78 60 89 67 60 91
    }
    std::cout << std::endl;
}

5. 치환 알고리즘 정리

알고리즘 비교

알고리즘원본 수정조건시간 복잡도
replace값 비교O(n)
replace_ifPredicateO(n)
replace_copy값 비교O(n)
replace_copy_ifPredicateO(n)

함수 시그니처

// 값 치환 (원본 수정)
template<class ForwardIt, class T>
void replace(ForwardIt first, ForwardIt last,
             const T& old_value, const T& new_value);

// 조건 치환 (원본 수정)
template<class ForwardIt, class UnaryPredicate, class T>
void replace_if(ForwardIt first, ForwardIt last,
                UnaryPredicate pred, const T& new_value);

// 복사하며 값 치환
template<class InputIt, class OutputIt, class T>
OutputIt replace_copy(InputIt first, InputIt last, OutputIt d_first,
                      const T& old_value, const T& new_value);

// 복사하며 조건 치환
template<class InputIt, class OutputIt, class UnaryPredicate, class T>
OutputIt replace_copy_if(InputIt first, InputIt last, OutputIt d_first,
                         UnaryPredicate pred, const T& new_value);

6. 자주 발생하는 문제

문제 1: 원본 수정 vs 복사

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

int main() {
    std::vector<int> v = {1, 2, 3, 2, 4};
    
    // replace: 원본 수정
    std::replace(v.begin(), v.end(), 2, 9);
    std::cout << "원본 수정: ";
    for (int x : v) {
        std::cout << x << " ";  // 1 9 3 9 4
    }
    std::cout << std::endl;
    
    // ✅ 원본 유지하려면 replace_copy
    std::vector<int> v2 = {1, 2, 3, 2, 4};
    std::vector<int> dst;
    std::replace_copy(v2.begin(), v2.end(), 
                      std::back_inserter(dst), 2, 9);
    
    std::cout << "원본: ";
    for (int x : v2) {
        std::cout << x << " ";  // 1 2 3 2 4 (변경 없음)
    }
    std::cout << std::endl;
}

문제 2: 여러 값 치환

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    
    // ❌ 비효율적: 여러 번 순회
    std::replace(v.begin(), v.end(), 2, 0);
    std::replace(v.begin(), v.end(), 4, 0);
    
    // ✅ 효율적: 한 번 순회
    std::vector<int> v2 = {1, 2, 3, 4, 5};
    std::replace_if(v2.begin(), v2.end(),
         { return x == 2 || x == 4; }, 0);
    
    for (int x : v2) {
        std::cout << x << " ";  // 1 0 3 0 5
    }
    std::cout << std::endl;
}

문제 3: std::string::replace와 혼동

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

int main() {
    std::string text = "hello world";
    
    // std::replace (알고리즘): 문자 하나씩 치환
    std::replace(text.begin(), text.end(), 'l', 'L');
    std::cout << text << std::endl;  // heLLo worLd
    
    // std::string::replace (멤버 함수): 부분 문자열 치환
    text.replace(0, 5, "HELLO");
    std::cout << text << std::endl;  // HELLO worLd
    
    // 다른 기능!
}

문제 4: 반복자 무효화

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    
    // ✅ replace는 반복자를 무효화하지 않음
    auto it = v.begin();
    std::replace(v.begin(), v.end(), 3, 99);
    
    std::cout << *it << std::endl;  // 1 (여전히 유효)
    
    // 주의: 크기 변경 연산(insert, erase)은 반복자 무효화
}

7. transform vs replace

차이점

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

int main() {
    std::vector<int> v1 = {1, 2, 3, 4, 5};
    std::vector<int> v2 = {1, 2, 3, 4, 5};
    
    // replace: 특정 값만 치환
    std::replace(v1.begin(), v1.end(), 2, 9);
    std::cout << "replace: ";
    for (int x : v1) {
        std::cout << x << " ";  // 1 9 3 4 5
    }
    std::cout << std::endl;
    
    // transform: 모든 요소 변환
    std::transform(v2.begin(), v2.end(), v2.begin(),
         { return x * 2; });
    std::cout << "transform: ";
    for (int x : v2) {
        std::cout << x << " ";  // 2 4 6 8 10
    }
    std::cout << std::endl;
}

언제 무엇을 사용할까

상황사용할 알고리즘
특정 값을 다른 값으로replace
조건에 맞는 값만 치환replace_if
모든 요소를 변환transform
원본 유지하며 치환replace_copy

8. 실전 예제: 데이터 전처리

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

class DataPreprocessor {
public:
    // 이상치 제거 (평균으로 치환)
    static void replaceOutliers(std::vector<double>& data, double threshold) {
        double mean = std::accumulate(data.begin(), data.end(), 0.0) / data.size();
        
        std::replace_if(data.begin(), data.end(),
            [mean, threshold](double x) {
                return std::abs(x - mean) > threshold;
            }, mean);
    }
    
    // 음수를 0으로
    static void replaceNegatives(std::vector<int>& data) {
        std::replace_if(data.begin(), data.end(),
             { return x < 0; }, 0);
    }
    
    // 결측치 처리
    static void replaceMissing(std::vector<int>& data, int missingValue, int replacement) {
        std::replace(data.begin(), data.end(), missingValue, replacement);
    }
};

int main() {
    // 센서 데이터
    std::vector<double> temperatures = {23.5, 24.0, 100.0, 23.8, 24.2, -50.0, 24.5};
    
    std::cout << "원본: ";
    for (double t : temperatures) {
        std::cout << t << " ";
    }
    std::cout << std::endl;
    
    // 이상치 제거 (평균에서 50 이상 차이)
    DataPreprocessor::replaceOutliers(temperatures, 50.0);
    
    std::cout << "전처리 후: ";
    for (double t : temperatures) {
        std::cout << t << " ";
    }
    std::cout << std::endl;
}

정리

핵심 요약

  1. replace: 특정 값을 다른 값으로 치환 (원본 수정)
  2. replace_if: 조건에 맞는 값 치환
  3. replace_copy: 복사하며 치환 (원본 유지)
  4. replace_copy_if: 복사하며 조건 치환
  5. 시간 복잡도: 모두 O(n)

실전 팁

  1. 선택 기준

    • 원본 수정 가능: replace, replace_if
    • 원본 유지: replace_copy, replace_copy_if
    • 특정 값: replace, replace_copy
    • 조건 기반: replace_if, replace_copy_if
  2. 성능 최적화

    • 여러 값 치환 시 replace_if 사용
    • 단일 패스로 처리
    • 불필요한 복사 피하기
  3. 주의사항

    • std::string::replace와 다름
    • 반복자는 유효 (크기 변경 없음)
    • Predicate는 부작용 없어야 함

다음 단계


관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ Algorithm Replace | ‘치환 알고리즘’ 가이드」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ Algorithm Replace | ‘치환 알고리즘’ 가이드」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. C++ replace, replace_if, replace_copy로 범위 치환. 원본 수정과 복사본 생성의 차이·조건 치환 실무 예를 다룹니다. C++·알고리즘·replace 중심으로 설명합니다. Start now… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, 알고리즘, replace, transform, STL 등으로 검색하시면 이 글이 도움이 됩니다.