Algorithms in C++ STL

The C++ Standard Template Library (STL) includes a powerful collection of ready-made algorithms in the <algorithm> header. These are general-purpose functions that work on data stored in containers through iterators. You do not write sorting, searching, or counting logic from scratch — the STL algorithms do it for you, correctly and efficiently.

Think of STL algorithms like tools in a toolbox. Instead of building a hammer yourself every time you need to drive a nail, you just pick up the hammer that is already there.

How STL Algorithms Work

Every STL algorithm takes a range defined by two iterators: a begin iterator and an end iterator. The algorithm operates on all elements from begin up to (but not including) end.

algorithm_name(container.begin(), container.end(), ...);
Vector: [10][20][30][40][50]
          ↑                 ↑
        begin()           end()
        Algorithm works on all elements in this range

Sorting — sort()

sort() arranges elements in ascending order by default. It uses an efficient hybrid sorting algorithm internally.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {40, 10, 30, 20, 50};

    sort(v.begin(), v.end());   // ascending

    for (auto n : v) cout << n << " ";
    cout << endl;

    sort(v.begin(), v.end(), greater<int>());  // descending

    for (auto n : v) cout << n << " ";
    cout << endl;

    return 0;
}

Output:

10 20 30 40 50
50 40 30 20 10

Searching — find() and binary_search()

find() — linear search:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30, 40, 50};

    auto it = find(v.begin(), v.end(), 30);

    if (it != v.end()) {
        cout << "Found 30 at index: " << (it - v.begin()) << endl;
    } else {
        cout << "Not found." << endl;
    }

    return 0;
}

Output:

Found 30 at index: 2

binary_search() — fast search on a sorted container:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30, 40, 50};   // must be sorted

    cout << binary_search(v.begin(), v.end(), 30) << endl;  // 1 (found)
    cout << binary_search(v.begin(), v.end(), 35) << endl;  // 0 (not found)

    return 0;
}

Output:

1
0

Counting — count() and count_if()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {10, 20, 10, 30, 10, 40};

    cout << "Count of 10: " << count(v.begin(), v.end(), 10) << endl;

    // count elements greater than 15
    int c = count_if(v.begin(), v.end(), [](int x){ return x > 15; });
    cout << "Elements > 15: " << c << endl;

    return 0;
}

Output:

Count of 10: 3
Elements > 15: 3

Minimum and Maximum — min_element(), max_element()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {30, 10, 50, 20, 40};

    auto minIt = min_element(v.begin(), v.end());
    auto maxIt = max_element(v.begin(), v.end());

    cout << "Min: " << *minIt << endl;
    cout << "Max: " << *maxIt << endl;

    return 0;
}

Output:

Min: 10
Max: 50

Filling and Replacing — fill(), replace()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v(5);
    fill(v.begin(), v.end(), 7);  // fill all elements with 7

    for (auto n : v) cout << n << " ";
    cout << endl;

    replace(v.begin(), v.end(), 7, 99);  // replace all 7s with 99

    for (auto n : v) cout << n << " ";
    cout << endl;

    return 0;
}

Output:

7 7 7 7 7
99 99 99 99 99

Reversing — reverse()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {10, 20, 30, 40, 50};

    reverse(v.begin(), v.end());

    for (auto n : v) cout << n << " ";
    cout << endl;

    return 0;
}

Output:

50 40 30 20 10

Copying — copy()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> src = {1, 2, 3, 4, 5};
    vector<int> dst(5);

    copy(src.begin(), src.end(), dst.begin());

    for (auto n : dst) cout << n << " ";
    cout << endl;

    return 0;
}

Output:

1 2 3 4 5

Transforming — transform()

transform() applies a function to every element and stores the result in a destination container.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

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

    transform(v.begin(), v.end(), result.begin(), [](int x) {
        return x * x;   // square each element
    });

    for (auto n : result) cout << n << " ";
    cout << endl;

    return 0;
}

Output:

1 4 9 16 25

Removing Duplicates — unique()

unique() removes consecutive duplicates. Sort first to group all duplicates together.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    vector<int> v = {10, 10, 20, 30, 30, 30, 40};

    auto newEnd = unique(v.begin(), v.end());
    v.erase(newEnd, v.end());   // erase leftover elements

    for (auto n : v) cout << n << " ";
    cout << endl;

    return 0;
}

Output:

10 20 30 40

Accumulate — sum and product (in <numeric>)

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

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

    int total = accumulate(v.begin(), v.end(), 0);   // 0 is starting value
    cout << "Sum: " << total << endl;

    int product = accumulate(v.begin(), v.end(), 1, multiplies<int>());
    cout << "Product: " << product << endl;

    return 0;
}

Output:

Sum: 15
Product: 120

Quick Reference — Common STL Algorithms

AlgorithmHeaderPurpose
sort()<algorithm>Sort elements in a range
find()<algorithm>Find first occurrence of a value
binary_search()<algorithm>Check if value exists (sorted range)
count()<algorithm>Count occurrences of a value
count_if()<algorithm>Count elements matching a condition
min_element()<algorithm>Iterator to smallest element
max_element()<algorithm>Iterator to largest element
reverse()<algorithm>Reverse elements in a range
fill()<algorithm>Set all elements to a value
replace()<algorithm>Replace a specific value with another
copy()<algorithm>Copy range into another container
transform()<algorithm>Apply a function to each element
unique()<algorithm>Remove consecutive duplicates
accumulate()<numeric>Sum or fold over a range

Key Takeaways

  • STL algorithms in <algorithm> provide ready-made, efficient operations on containers.
  • All algorithms work through iterators — they accept begin() and end() as range parameters.
  • sort() sorts ascending by default; pass greater<T>() for descending.
  • Always sort before using binary_search() or unique().
  • Lambda functions pair naturally with algorithms like count_if() and transform().
  • accumulate() lives in <numeric>, not <algorithm>.

Leave a Comment

Your email address will not be published. Required fields are marked *