TExcelTAD
Home › C++ › C++ Algorithms

C++ Algorithms

The <algorithm> header (plus <numeric>) contains over a hundred ready-made, well-tested, highly optimised functions for searching, sorting, counting, transforming and more. They operate on iterator ranges, so they work with any container. Reaching for an algorithm instead of writing a raw loop makes code shorter, clearer and less buggy.

Sorting

cpp · try it yourself
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;

int main() {
    vector<int> v = {42, 7, 19, 3, 25, 11};

    sort(v.begin(), v.end());
    for (int x : v) cout << x << " ";
    cout << "\n";

    sort(v.begin(), v.end(), greater<int>());       // descending
    for (int x : v) cout << x << " ";
    cout << "\n";

    struct Player { string name; int score; };
    vector<Player> ps = {{"Ana", 80}, {"Bo", 95}, {"Cy", 80}, {"Di", 70}};
    stable_sort(ps.begin(), ps.end(),
                [](const Player& a, const Player& b) { return a.score > b.score; });
    for (const auto& p : ps) cout << p.name << "(" << p.score << ") ";
    cout << "\n";
}
3 7 11 19 25 42
42 25 19 11 7 3
Bo(95) Ana(80) Cy(80) Di(70)

stable_sort keeps equal elements (Ana and Cy) in their original order; plain sort makes no such guarantee.

Searching and counting

Algorithm Returns
find(b, e, x) iterator to the first x, or e
find_if(b, e, pred) iterator to the first element where pred is true
count(b, e, x) / count_if(b, e, pred) number of matches
any_of / all_of / none_of bool
min_element / max_element iterator to the smallest / largest
binary_search(b, e, x) bool — range must be sorted
cpp · try it yourself
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> temps = {18, 23, 31, 27, 15, 33, 22};

    auto hot = find_if(temps.begin(), temps.end(), [](int t) { return t > 30; });
    cout << "first hot day: index " << (hot - temps.begin()) << " (" << *hot << ")\n";

    cout << "days above 20: "
         << count_if(temps.begin(), temps.end(), [](int t) { return t > 20; }) << "\n";

    cout << boolalpha
         << "any freezing? " << any_of(temps.begin(), temps.end(), [](int t) { return t <= 0; }) << "\n";

    auto [lo, hi] = minmax_element(temps.begin(), temps.end());
    cout << "min " << *lo << ", max " << *hi << "\n";
}
first hot day: index 2 (31)
days above 20: 5
any freezing? false
min 15, max 33

Transforming and accumulating

transform applies a function to every element; accumulate (from <numeric>) folds a range into one value:

cpp · try it yourself
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;

int main() {
    vector<double> prices = {9.99, 24.50, 3.25};
    vector<double> withTax(prices.size());
    transform(prices.begin(), prices.end(), withTax.begin(),
              [](double p) { return p * 1.2; });
    for (double p : withTax) cout << p << " ";
    cout << "\n";

    double total = accumulate(prices.begin(), prices.end(), 0.0);
    cout << "total: " << total << "\n";

    vector<string> words = {"alpha", "beta", "gamma"};
    string joined = accumulate(next(words.begin()), words.end(), words[0],
                               [](const string& acc, const string& w) { return acc + "-" + w; });
    cout << joined << "\n";

    vector<int> ids(5);
    iota(ids.begin(), ids.end(), 100);      // 100, 101, 102, ...
    for (int id : ids) cout << id << " ";
    cout << "\n";
}
11.988 29.4 3.9
total: 37.74
alpha-beta-gamma
100 101 102 103 104

Tip: Pass 0.0, not 0, as the start value of accumulate for doubles. The start value decides the type used for the running sum, and 0 would truncate every step to an int.

Modifying sequences

cpp · try it yourself
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void print(const vector<int>& v) {
    for (int x : v) cout << x << " ";
    cout << "\n";
}

int main() {
    vector<int> v = {5, 3, 5, 1, 3, 3, 9};

    reverse(v.begin(), v.end());            print(v);
    replace(v.begin(), v.end(), 3, 0);      print(v);

    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()), v.end());   // remove duplicates
    print(v);

    erase(v, 0);                            // C++20: remove all zeros
    print(v);

    rotate(v.begin(), v.begin() + 1, v.end());
    print(v);
}
9 3 3 1 5 3 5
9 0 0 1 5 0 5
0 1 5 9
1 5 9
5 9 1

unique does not actually shrink the vector — it moves the unique elements to the front and returns the new logical end. The erase(unique(...), end) combination is a well-known idiom.

Ranges (C++20)

C++20 adds range versions of the algorithms in namespace std::ranges. You pass the container directly instead of begin()/end(), and you can compose lazy views:

cpp · try it yourself
#include <iostream>
#include <vector>
#include <algorithm>
#include <ranges>
using namespace std;

int main() {
    vector<int> v = {8, 3, 6, 1, 9, 4, 7};
    ranges::sort(v);
    for (int x : v) cout << x << " ";
    cout << "\n";

    auto evenSquares = v | views::filter([](int x) { return x % 2 == 0; })
                         | views::transform([](int x) { return x * x; });
    for (int x : evenSquares) cout << x << " ";
    cout << "\n";

    cout << boolalpha << (ranges::find(v, 9) != v.end()) << "\n";
}
1 3 4 6 7 8 9
16 36 64
true

Test yourself

What is the difference between sort and stable_sort?

  1. stable_sort is always faster
  2. stable_sort keeps equal elements in their original order
  3. sort only works on vectors
  4. There is no difference

What does find return when the value is not present?

  1. -1
  2. nullptr
  3. The end iterator of the range
  4. It throws

Which header contains accumulate and iota?

  1. <algorithm>
  2. <numeric>
  3. <functional>
  4. <iterator>