C++ STL 알고리즘 | "자주 쓰는 함수" 20개 총정리

C++ STL 알고리즘 | "자주 쓰는 함수" 20개 총정리

이 글의 핵심

C++ STL 알고리즘에 대해 정리한 개발 블로그 글입니다. #include <algorithm> #include <vector> using namespace std;

STL 알고리즘 20선

1. sort - 정렬

#include <algorithm>
#include <vector>
using namespace std;

vector<int> v = {3, 1, 4, 1, 5};
sort(v.begin(), v.end());  // 오름차순
sort(v.begin(), v.end(), greater<int>());  // 내림차순

2. find - 검색

auto it = find(v.begin(), v.end(), 3);
if (it != v.end()) {
    cout << "찾음: " << *it << endl;
}

3. binary_search - 이진 탐색

sort(v.begin(), v.end());  // 정렬 필수
bool found = binary_search(v.begin(), v.end(), 3);

4. lower_bound / upper_bound

auto it = lower_bound(v.begin(), v.end(), 3);  // >= 3인 첫 위치
auto it2 = upper_bound(v.begin(), v.end(), 3);  // > 3인 첫 위치

5. count - 개수 세기

int cnt = count(v.begin(), v.end(), 1);  // 1의 개수

6. accumulate - 합계

#include <numeric>
int sum = accumulate(v.begin(), v.end(), 0);

7. max_element / min_element

auto maxIt = max_element(v.begin(), v.end());
auto minIt = min_element(v.begin(), v.end());
cout << "최댓값: " << *maxIt << endl;

8. reverse - 역순

reverse(v.begin(), v.end());

9. unique - 중복 제거

sort(v.begin(), v.end());
auto it = unique(v.begin(), v.end());
v.erase(it, v.end());

10. fill - 값 채우기

fill(v.begin(), v.end(), 0);  // 모두 0으로

11. copy - 복사

vector<int> v2(v.size());
copy(v.begin(), v.end(), v2.begin());

12. transform - 변환

transform(v.begin(), v.end(), v.begin(),  { return x * 2; });

13. for_each - 각 요소에 함수 적용

for_each(v.begin(), v.end(),  { cout << x << " "; });

14. remove / remove_if

auto it = remove(v.begin(), v.end(), 3);  // 3 제거
v.erase(it, v.end());

auto it2 = remove_if(v.begin(), v.end(),  { return x % 2 == 0; });
v.erase(it2, v.end());

15. replace - 치환

replace(v.begin(), v.end(), 1, 10);  // 1을 10으로

16. next_permutation - 순열

vector<int> v = {1, 2, 3};
do {
    for (int x : v) cout << x;
    cout << " ";
} while (next_permutation(v.begin(), v.end()));

17. partition - 분할

partition(v.begin(), v.end(),  { return x % 2 == 0; });

18. merge - 병합

vector<int> result(v1.size() + v2.size());
merge(v1.begin(), v1.end(), v2.begin(), v2.end(), result.begin());

19. all_of / any_of / none_of

bool allPositive = all_of(v.begin(), v.end(),  { return x > 0; });
bool hasNegative = any_of(v.begin(), v.end(),  { return x < 0; });
bool noZero = none_of(v.begin(), v.end(),  { return x == 0; });

20. minmax_element - 최소/최대 동시

auto [minIt, maxIt] = minmax_element(v.begin(), v.end());
cout << "최소: " << *minIt << ", 최대: " << *maxIt << endl;

실전 예시

예시 1: 데이터 정제 파이프라인

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

int main() {
    vector<int> data = {5, -2, 8, -1, 3, 0, 7, -3, 2, 8, 5};
    
    cout << "원본: ";
    for (int x : data) cout << x << " ";
    
    // 1. 음수 제거
    auto it = remove_if(data.begin(), data.end(),  { return x < 0; });
    data.erase(it, data.end());
    
    // 2. 정렬
    sort(data.begin(), data.end());
    
    // 3. 중복 제거
    auto it2 = unique(data.begin(), data.end());
    data.erase(it2, data.end());
    
    cout << "\n정제 후: ";
    for (int x : data) cout << x << " ";
    
    // 4. 통계
    int sum = accumulate(data.begin(), data.end(), 0);
    double avg = (double)sum / data.size();
    
    cout << "\n합계: " << sum << endl;
    cout << "평균: " << avg << endl;
    cout << "최댓값: " << *max_element(data.begin(), data.end()) << endl;
    
    return 0;
}

설명: 여러 알고리즘을 조합하여 데이터를 정제하는 파이프라인입니다.

예시 2: 학생 정렬 시스템

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

struct Student {
    string name;
    int score;
    int id;
};

int main() {
    vector<Student> students = {
        {"Alice", 85, 1003},
        {"Bob", 92, 1001},
        {"Charlie", 85, 1002},
        {"David", 78, 1004}
    };
    
    // 점수 내림차순, 같으면 ID 오름차순
    sort(students.begin(), students.end(),  {
        if (a.score != b.score) return a.score > b.score;
        return a.id < b.id;
    });
    
    cout << "=== 성적 순위 ===" << endl;
    for (int i = 0; i < students.size(); i++) {
        cout << (i+1) << "등: " << students[i].name 
             << " (" << students[i].score << "점)" << endl;
    }
    
    // 80점 이상 학생 수
    int count = count_if(students.begin(), students.end(), 
                          { return s.score >= 80; });
    cout << "\n80점 이상: " << count << "명" << endl;
    
    // 평균 점수
    int totalScore = accumulate(students.begin(), students.end(), 0,
                                 { return sum + s.score; });
    cout << "평균: " << (double)totalScore / students.size() << "점" << endl;
    
    return 0;
}

설명: 복잡한 정렬 조건과 집계 함수를 활용한 실무 패턴입니다.

예시 3: 문자열 처리

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;

int main() {
    string text = "Hello World 123";
    
    // 대문자로 변환
    transform(text.begin(), text.end(), text.begin(), ::toupper);
    cout << text << endl;  // HELLO WORLD 123
    
    // 숫자만 추출
    string numbers;
    copy_if(text.begin(), text.end(), back_inserter(numbers), ::isdigit);
    cout << "숫자: " << numbers << endl;  // 123
    
    // 공백 제거
    auto it = remove(text.begin(), text.end(), ' ');
    text.erase(it, text.end());
    cout << "공백 제거: " << text << endl;
    
    // 회문 체크
    string original = "level";
    string reversed = original;
    reverse(reversed.begin(), reversed.end());
    
    if (original == reversed) {
        cout << original << "은 회문입니다" << endl;
    }
    
    return 0;
}

설명: 문자열 변환과 필터링에 STL 알고리즘을 활용한 예제입니다.

자주 발생하는 문제

문제 1: remove는 실제로 삭제하지 않음

증상: remove 후에도 벡터 크기가 그대로

원인: remove는 요소를 뒤로 이동만 하고 erase가 실제 삭제

해결법:

// ❌ 잘못된 사용
vector<int> v = {1, 2, 3, 2, 4};
remove(v.begin(), v.end(), 2);
cout << v.size();  // 5 (그대로!)

// ✅ 올바른 사용 (erase-remove idiom)
vector<int> v = {1, 2, 3, 2, 4};
auto it = remove(v.begin(), v.end(), 2);
v.erase(it, v.end());
cout << v.size();  // 3

증상: binary_search가 잘못된 결과 반환

원인: 이진 탐색은 정렬된 데이터에서만 동작

해결법:

// ❌ 잘못된 코드
vector<int> v = {3, 1, 4, 1, 5};
bool found = binary_search(v.begin(), v.end(), 3);  // 잘못된 결과

// ✅ 올바른 코드
vector<int> v = {3, 1, 4, 1, 5};
sort(v.begin(), v.end());  // 정렬 먼저!
bool found = binary_search(v.begin(), v.end(), 3);  // OK

문제 3: 람다에서 외부 변수 캡처

증상: 람다 내부에서 외부 변수 사용 시 컴파일 에러

원인: 캡처를 명시하지 않음

해결법:

// ❌ 컴파일 에러
int threshold = 10;
auto it = find_if(v.begin(), v.end(),  {
    return x > threshold;  // 에러! threshold 캡처 안됨
});

// ✅ 값 캡처
auto it = find_if(v.begin(), v.end(), [threshold](int x) {
    return x > threshold;
});

// ✅ 참조 캡처
auto it = find_if(v.begin(), v.end(), [&threshold](int x) {
    return x > threshold;
});

// ✅ 모두 캡처
auto it = find_if(v.begin(), v.end(), [=](int x) {  // 값으로 모두
    return x > threshold;
});

auto it = find_if(v.begin(), v.end(), [&](int x) {  // 참조로 모두
    return x > threshold;
});

FAQ

Q1: sort는 어떤 알고리즘을 사용하나요?

A: Introsort (퀵소트 + 힙소트 + 삽입정렬)를 사용하며, 평균 O(n log n)입니다.

Q2: stable_sort는 언제 사용하나요?

A: 같은 값의 상대적 순서를 유지해야 할 때 사용합니다.

vector<pair<int,int>> v = {{1,1}, {2,1}, {1,2}};
stable_sort(v.begin(), v.end());  // {1,1}, {1,2}, {2,1}

Q3: for_each vs 범위 기반 for?

A: 대부분 범위 기반 for가 더 간단합니다.

// for_each
for_each(v.begin(), v.end(),  { cout << x; });

// 범위 기반 for (더 간단)
for (int x : v) cout << x;

Q4: 왜 algorithm을 사용해야 하나요?

A:

  • 최적화되어 있음 (직접 구현보다 빠름)
  • 버그 없음 (검증됨)
  • 코드가 간결함
  • 의도가 명확함

Q5: 커스텀 비교 함수는 어떻게 만드나요?

A: 람다, 함수 객체, 함수 포인터 모두 가능합니다.

// 람다
sort(v.begin(), v.end(),  { return a > b; });

// 함수 객체
struct Greater {
    bool operator()(int a, int b) { return a > b; }
};
sort(v.begin(), v.end(), Greater());

// 함수 포인터
bool greater(int a, int b) { return a > b; }
sort(v.begin(), v.end(), greater);

Q6: 성능이 중요한 경우 팁은?

A:

  • 정렬 횟수 최소화
  • reserve()로 재할당 방지
  • 참조 캡처 사용
  • 불필요한 복사 제거

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

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

  • C++ 알고리즘 | “STL algorithm” 핵심 정리
  • C++ Algorithm Search | “검색 알고리즘” 가이드
  • C++ Algorithm Copy | “복사 알고리즘” 가이드

관련 글

  • C++ Algorithm Copy |
  • C++ Algorithm Count |
  • C++ Algorithm Generate |
  • C++ 알고리즘 |
  • C++ Algorithm Heap |