STL Containers and Algorithms in C++ vs Loops in C
Replace hand-written loops with copy_if, accumulate and sort. Clearer code, same speed.
- std::vector and iterator ranges
- copy_if, accumulate and sort
- How this compares with a manual C loop
- 1
{3, 8, 2, 7, 6}Input vector - 2
copy_if(..., is_even)Keep the even values - 3
{8, 2, 6}Filtered: count = 3 - 4
accumulate(...) → 16Add them up
Algorithms work on ranges
The problem
Filtering, summing, sorting and searching are written again and again with hand-made loops, and each loop is a chance for an off-by-one error. The C++ standard library provides tested algorithms for these tasks.
Think of it like this
STL algorithms are like kitchen appliances. Instead of whisking by hand every time, you put ingredients in a mixer and press a button. Containers are the bowls; algorithms are the appliances that work with any bowl.
values🥣 A bowl of ingredientsstd::copy_if(...)🧺 A sieve: keep only what passesstd::accumulate(...)⚖️ A scale: add everything upbegin(), end()📏 Which part of the bowl to useThe C++ Standard Template Library (STL) provides containers such as std::vector and algorithms such as std::copy_if and std::accumulate that work on any range given by begin and end iterators.
Important points
- The C version writes two loops: one to filter into
even, one to sum. std::copy_ifcopies only values where the lambda returns true, usingstd::back_inserterto groweven.std::accumulateadds the values ineven, starting from 0.- Both print count=3 and sum=16.
When to use it
- Filtering, transforming, sorting and searching collections.
- Replacing hand-written loops with tested, readable calls.
- Working the same way with vectors, arrays, lists and more.
When not to use it
- C code: there is no STL, so loops are written by hand.
- A combination so complex that a plain loop is clearer to read.
C and C++ code examples
#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
#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
The C version uses one loop to copy the even values into an array and another to add them. In C++, std::copy_if does the filtering with a lambda and std::back_inserter grows the even vector as needed. std::accumulate then adds the three even values, 8, 2 and 6, to get 16.
C uses naming conventions, callbacks, macros, and explicit context structures.
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.
Common mistakes
Copying into an empty vector without an inserter
Writing to even.begin() of an empty vector writes past its end.
std::copy_if(values.begin(), values.end(), even.begin(), is_even);
std::copy_if(values.begin(), values.end(), std::back_inserter(even), is_even);
Wrong start type in accumulate
Starting with 0 sums as int, which truncates doubles.
std::accumulate(prices.begin(), prices.end(), 0);
std::accumulate(prices.begin(), prices.end(), 0.0);
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Median of a List Find the middle value of a list after sorting. Easy
- Second Largest Value Find the second largest distinct value. Easy