STL Containers and Algorithms
C++ algorithms operate on iterator ranges, separating operations from container storage.
What is STL Containers and Algorithms?
C++ algorithms operate on iterator ranges, separating operations from container storage.
Compare manual array processing with composable standard algorithms.
Important points
- Understand the C mechanism before comparing the C++ abstraction.
- Use RAII and value semantics to express ownership.
- Prefer type-safe compile-time abstractions over macros and casts.
C and C++ code examples
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 and C++ comparison
C exposes all loop and capacity details directly. C++ composes copy_if and accumulate over vector iterators, improving reuse while retaining predictable complexity.
C
C uses naming conventions, callbacks, macros, and explicit context structures.
C++
Language features provide scoped, type-safe, and often zero-overhead abstractions.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Write the C mechanism before the C++ abstraction.
- Remove manual cleanup with RAII.
- Check whether the abstraction adds allocations or virtual dispatch.