C++ STL Algorithms

sort, find, count_if, accumulate and more.

✍️ 2 exercises in this lesson

<algorithm> and <numeric> provide tested, fast algorithms that work on containers:

  • std::sort(), std::reverse()
  • std::find(), std::count_if(), std::any_of()
  • std::accumulate(): sum or combine values
  • std::transform(): map values into another container

Pass lambdas to customise them.

Key Takeaways: C++ STL Algorithms

Mastering C++ STL Algorithms helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ STL Algorithms Code Example

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

int main() {
    std::vector<int> v = {72, 95, 58, 88, 64};

    std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
    int passed = std::count_if(v.begin(), v.end(), [](int m) { return m >= 60; });
    int total = std::accumulate(v.begin(), v.end(), 0);
    bool anyFail = std::any_of(v.begin(), v.end(), [](int m) { return m < 60; });

    for (int m : v) std::cout << m << " ";
    std::cout << "\nPassed: " << passed << ", total: " << total
              << ", any fail: " << std::boolalpha << anyFail << "\n";
    return 0;
}
Output
95 88 72 64 58 
Passed: 4, total: 377, any fail: true
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ STL Algorithms Practice Exercises

Check what you learned in “C++ STL Algorithms”.

/ 2 solved
Fill in the blank

Sort a vector.

std::(v.begin(), v.end());
✓ Correct! Not quite. Try again.
Multiple choice

Which header provides std::accumulate?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services