01 / 21
<algorithm>

STL Algorithms

Master the power of <algorithm> in C++: learn to sort, find, and count with clean, expressive code that replaces hand-written loops.

C++

What Are STL Algorithms?

The Standard Template Library (STL) provides a collection of pre-built functions in the <algorithm> header that operate on ranges of elements. Instead of writing loops by hand, you call a well-tested function.

Why Use STL Algorithms?

Readability
Code clearly states what you want, not how to loop. A call to std::sort is instantly understood.
Reliability
These functions are battle-tested by millions of developers. Fewer bugs than hand-rolled loops.
Performance
Implementations are highly optimized. std::sort is typically \( O(n \log n) \) with excellent real-world speed.

The Iterator Pattern

5 3 8 1 9 2 begin() end() std::vector<int> v = {5, 3, 8, 1, 9, 2}; range: [begin, end)

The Big Three: sort, find, count

std::sort Reorders elements in ascending order Complexity:
\( O(n \log n) \)
Returns: void std::find Searches for a specific value Complexity:
\( O(n) \)
Returns: iterator std::count Counts occurrences of a value Complexity:
\( O(n) \)
Returns: integer

std::sort: Syntax and Behavior

#include <algorithm>
#include <vector>

std::vector<int> v = {5, 3, 8, 1, 9, 2};

// Sort ascending (default)
std::sort(v.begin(), v.end());
// v is now {1, 2, 3, 5, 8, 9}

// Sort descending with comparator
std::sort(v.begin(), v.end(), std::greater<int>());
// v is now {9, 8, 5, 3, 2, 1}

std::find: Searching for a Value

std::vector<int> v = {5, 3, 8, 1, 9, 2};

auto it = std::find(v.begin(), v.end(), 8);

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

std::count: Counting Occurrences

std::vector<int> v = {3, 7, 3, 5, 3, 9};

int n = std::count(v.begin(), v.end(), 3);

std::cout << n; // Output: 3

find vs count: When to Use Each

std::find
Use when you need to know where an element is, or need to check existence. Stops at the first match (can be faster than count).
std::count
Use when you need to know how many times a value appears. Always scans the entire range, even after finding the first match.

How to Apply STL Algorithms

1
Include the header. Add #include <algorithm> at the top of your file.
2
Identify your range. Decide which container and which portion you want to process: begin() to end(), or a sub-range.
3
Choose the right algorithm. Need ordering? Use sort. Need to locate? Use find. Need a tally? Use count.
4
Handle the return value. Sort returns void. Find returns an iterator (check against end!). Count returns an integer.
5
Test edge cases. Empty containers, values not found, and containers with all identical elements.

Example 1: Sort Student Scores

#include <algorithm>
#include <vector>
#include <iostream>

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

  std::sort(scores.begin(), scores.end());

  for (int s : scores)
    std::cout << s << " ";
  // Output: 64 72 81 88 95
}

Example 2: Find a Target Value

std::vector<std::string> names = {"Alice", "Bob", "Carol"};

auto it = std::find(names.begin(), names.end(), "Bob");

if (it != names.end()) {
  std::cout << "Found " << *it
           << " at position "
           << (it - names.begin());
  // Output: Found Bob at position 1
}

Example 3: Count and Sort Together

std::vector<int> data = {4, 2, 7, 2, 9, 2, 5};

// Count how many 2s exist
int twos = std::count(data.begin(), data.end(), 2);
std::cout << "Twos: " << twos; // 3

// Sort then find the first 2
std::sort(data.begin(), data.end());
// data: {2, 2, 2, 4, 5, 7, 9}

auto it = std::find(data.begin(), data.end(), 2);
// it points to index 0

Visualizing std::sort

BEFORE sort 5 3 8 1 9 2 std::sort(begin, end) AFTER sort 1 2 3 5 8 9

Common Mistakes

✕ Forgetting #include
Using std::sort without #include <algorithm> causes a compiler error. Always include the header.
✕ Dereferencing end()
When std::find returns end(), dereferencing it is undefined behavior. Always check it != v.end() first.
✕ Wrong Iterator Order
Passing end() before begin() causes undefined behavior. The first argument must come before the second in the range.

Summary Comparison Table

Feature std::sort std::find std::count
Purpose Order elements Locate a value Tally a value
Arguments begin, end [, comp] begin, end, value begin, end, value
Returns void iterator integer
Complexity \( O(n \log n) \) \( O(n) \) \( O(n) \)
Modifies data? Yes No No
Can stop early? N/A Yes No

Question 1 of 5

What does std::sort(v.begin(), v.end()) return?

Question 2 of 5

Given std::vector<int> v = {4, 7, 2, 7, 3}, what does std::count(v.begin(), v.end(), 7) return?

Question 3 of 5

What happens if you dereference the iterator returned by std::find when the value is not found in the container?

Question 4 of 5

Which header must you include to use std::sort, std::find, and std::count?

Question 5 of 5

You want to check if a std::vector contains the value 42, but you do not need to know how many times it appears. Which approach is most efficient?