Modern C++ and C Alternatives

STL Containers and Algorithms in C++ vs Loops in C

Replace hand-written loops with copy_if, accumulate and sort. Clearer code, same speed.

  • Advanced
  • 4 min read
  • 2 runnable examples
What you'll learn
  • std::vector and iterator ranges
  • copy_if, accumulate and sort
  • How this compares with a manual C loop
Sum of the even values
  1. 1{3, 8, 2, 7, 6}Input vector
  2. 2copy_if(..., is_even)Keep the even values
  3. 3{8, 2, 6}Filtered: count = 3
  4. 4accumulate(...) → 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.

From kitchen appliances to code
values🥣 A bowl of ingredients
std::copy_if(...)🧺 A sieve: keep only what passes
std::accumulate(...)⚖️ A scale: add everything up
begin(), end()📏 Which part of the bowl to use
Algorithms work on ranges, whatever the container.
In one sentence

The 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

  1. The C version writes two loops: one to filter into even, one to sum.
  2. std::copy_if copies only values where the lambda returns true, using std::back_inserter to grow even.
  3. std::accumulate adds the values in even, starting from 0.
  4. 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

C
Run 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);
}
Get a Run button for this example Result of running the code
count=3 sum=16
C++
Run 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';
}
Get a Run button for this example Result of running the code
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

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.

Common mistakes

Copying into an empty vector without an inserter

Writing to even.begin() of an empty vector writes past its end.

Problem
std::copy_if(values.begin(), values.end(), even.begin(), is_even);
Fix
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.

Problem
std::accumulate(prices.begin(), prices.end(), 0);
Fix
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.

All challenges