모던 C++와 C 대안

STL Container와 Algorithm

C++ algorithm은 iterator range에서 동작해 operation과 storage를 분리합니다.

STL Container와 Algorithm이란?

C++ algorithm은 iterator range에서 동작해 operation과 storage를 분리합니다.

수동 배열 처리와 조합 가능한 algorithm을 비교합니다.

중요한 점

  • 먼저 C 메커니즘을 이해하세요.
  • RAII와 value semantics로 ownership을 표현하세요.
  • Macro와 cast보다 type-safe 추상화를 사용하세요.

C와 C++ 코드 예제

C
실행 →
main.c
#include <stdio.h>

int main(void) {
    int values[] = {3, 8, 2, 7, 6};
    int even[5];
    int count = 0;
    int sum = 0;
    for (int index = 0; index < 5; ++index) {
        if (values[index] % 2 == 0) {
            even[count++] = values[index];
        }
    }
    for (int index = 0; index < count; ++index) {
        sum += even[index];
    }
    printf("count=%d sum=%d\n", count, sum);
}
예상 출력
count=3 sum=16
C++
실행 →
main.cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

int main() {
    std::vector values{3, 8, 2, 7, 6};
    std::vector<int> even;
    std::copy_if(values.begin(), values.end(),
                 std::back_inserter(even),
                 [](int value) { return value % 2 == 0; });
    std::cout << "count=" << even.size()
              << " sum="
              << std::accumulate(even.begin(), even.end(), 0) << '\n';
}
예상 출력
count=3 sum=16

C와 C++ 비교

C는 loop와 capacity를 명시합니다. C++는 copy_if, accumulate, vector를 재사용 가능하게 조합합니다.

C

C는 prefix, callback, macro와 context 구조를 씁니다.

C++

언어 기능이 scope와 type safety를 갖춘 추상화를 제공합니다.

연습 문제

두 버전을 실행하고 수정하여 각 언어의 보장을 관찰하세요.

  • C 메커니즘을 먼저 작성하세요.
  • 수동 cleanup을 RAII로 바꾸세요.
  • Allocation과 virtual dispatch를 확인하세요.