C++ hiện đại và cách làm tương ứng trong C

STL Container và Algorithm

C++ algorithm chạy trên iterator range, tách operation khỏi container storage.

STL Container và Algorithm là gì?

C++ algorithm chạy trên iterator range, tách operation khỏi container storage.

So sánh xử lý mảng thủ công với standard algorithm có thể kết hợp.

Điểm quan trọng

  • Hiểu cơ chế trong C trước khi học abstraction của C++.
  • Dùng RAII và value semantics để diễn đạt ownership.
  • Ưu tiên abstraction type-safe hơn macro và cast.

Code ví dụ bằng C và C++

C
Chạy code →
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);
}
Output dự kiến
count=3 sum=16
C++
Chạy code →
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';
}
Output dự kiến
count=3 sum=16

So sánh C và C++

C biểu diễn loop và capacity trực tiếp; C++ kết hợp copy_if, accumulate và vector để tái sử dụng mà vẫn có complexity rõ.

C

C dùng naming convention, callback, macro và context struct.

C++

Tính năng ngôn ngữ cung cấp abstraction có scope, type-safe và thường zero-overhead.

Bài tập mở rộng

Chạy cả hai phiên bản rồi thay đổi để quan sát khác biệt về bảo đảm của từng ngôn ngữ.

  • Viết cơ chế bằng C trước abstraction C++.
  • Loại bỏ manual cleanup bằng RAII.
  • Kiểm tra allocation hoặc virtual dispatch phát sinh.