Skip to content

Algorithms Operate on Ranges

The Course
•
35 min study

Reports ask the same few questions over and over: is there a task with 25 minutes, how many are done, where is the first long one. You can answer each with a hand-written loop, but every loop is a new place for an off-by-one mistake. The standard library's algorithms in <algorithm> (std::find, std::count, std::sort and many more) answer those questions once, correctly, for any container.

Algorithms do not take a container. They take a range: two iterators, one marking where to start and one marking where to stop. That design lets the same std::find search a vector, a map, part of a vector, or a plain array. It also means you need to understand exactly what the two positions mean and when they stop being valid.

Predict and run

std::find returns a position, and std::count returns a number. What is printed?

Predict before running C++
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{25, 10, 25};
    auto found = std::find(values.begin(), values.end(), 10);
    if (found != values.end()) { std::cout << *found << "\n"; }
    std::cout << std::count(values.begin(), values.end(), 25) << "\n";
    return 0;
}
Check your prediction
Text
10
2

found is an iterator to the 10, and *found reads it. Search for 99 instead: std::find returns values.end(), the if is skipped, and only the count line prints. Without the if, *found would dereference end(), which is undefined behavior.

Half-open ranges

begin() refers to the first element. end() refers to the position one past the last element; it marks the stop and holds no element. A range written [begin, end) therefore includes its start and excludes its end. That convention looks odd at first, but it makes the common cases fall out naturally:

  • An empty range is begin == end. A loop while (it != end) runs zero times with no special case.
  • The length is end - begin. For a vector, std::distance(values.begin(), found) is the index of the found element.
  • "Not found" needs no extra value. An algorithm returns end to say it reached the stop without a match.
  • Ranges split cleanly. [begin, middle) and [middle, end) cover everything exactly once.
Positions, indexes and partial ranges C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main() {
    std::vector<int> values{40, 10, 25, 10};
    auto found = std::find(values.begin(), values.end(), 10);
    std::cout << "First 10 at index " << std::distance(values.begin(), found) << "\n";
    auto later = std::find(found + 1, values.end(), 10);
    std::cout << "Next 10 at index " << std::distance(values.begin(), later) << "\n";
    std::cout << "25s in the first two: " << std::count(values.begin(), values.begin() + 2, 25) << "\n";
    std::vector<int> empty;
    std::cout << "Empty range: " << (empty.begin() == empty.end()) << "\n";
    return 0;
}
Text
First 10 at index 1
Next 10 at index 3
25s in the first two: 0
Empty range: 1

The second search starts just after the first match, which is how you find every occurrence. The count over [begin, begin + 2) looks at indexes 0 and 1 only, so the 25 at index 2 is excluded.

Iterator invalidation

An iterator is only valid while the container keeps its elements where they were. For a vector, push_back may reallocate and invalidate every iterator, and erase invalidates iterators to the erased element and everything after it. Using an invalidated iterator is undefined behavior. The classic trap is erasing inside a loop:

C++
for (auto it = values.begin(); it != values.end(); ++it) {
    if (*it < 15) { values.erase(it); } // it is now invalid, then ++it uses it.
}

erase returns an iterator to the element after the removed one, so the correct loop takes that return value and only advances when it did not erase. C++20 adds std::erase_if(container, predicate), which does the whole job in one call and returns how many elements it removed:

Erase while iterating, correctly C++
#include <iostream>
#include <vector>

bool is_short(int minutes) { return minutes < 15; }

int main() {
    std::vector<int> loop{10, 5, 25, 12, 40};
    for (auto it = loop.begin(); it != loop.end();) {
        if (is_short(*it)) { it = loop.erase(it); } else { ++it; }
    }
    std::vector<int> library{10, 5, 25, 12, 40};
    const auto removed = std::erase_if(library, is_short);
    std::cout << "Removed " << removed << "\n";
    for (int value : loop) { std::cout << value << " "; }
    std::cout << "| ";
    for (int value : library) { std::cout << value << " "; }
    std::cout << "\n";
    return 0;
}
Text
Removed 3
25 40 | 25 40

The broken loop above would also skip elements: after erasing the 10, the 5 slides into its place and ++it jumps past it. The tracker avoids the whole question in its reports by working on a snapshot, a copy of the tasks, and finishing each algorithm before anything changes the original.

Practice

Exercise

Your turn

Write bool contains(const std::vector<int>& values, int target) with std::find, and std::size_t remove_below(std::vector<int>& values, int limit) that erases every value below limit with an explicit iterator loop (not erase_if) and returns how many it removed. Expected output:

Text
contains 25: yes
contains 99: no
empty contains 25: no
removed 3, left: 25 15
Range checked

The removal starts from {10, 5, 25, 12, 15} with a limit of 15. Notice the two short values next to each other: they catch the skipping bug.

Your workspace C++
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>

// Write contains and remove_below here.

int main() {
    std::vector<int> values{10, 5, 25, 12, 15};
    return 0;
}
Hint 1: the idea

contains is a comparison of the returned position with end(). remove_below must never use an iterator after erase has invalidated it; use the iterator erase gives back instead.

Hint 2: a first step

Write the loop header without an increment: for (auto it = values.begin(); it != values.end();). In the body, either it = values.erase(it); ++removed; or ++it;, never both.

Show one solution
Run the solution C++
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>

bool contains(const std::vector<int>& values, int target) {
    return std::find(values.begin(), values.end(), target) != values.end();
}

std::size_t remove_below(std::vector<int>& values, int limit) {
    std::size_t removed = 0;
    for (auto it = values.begin(); it != values.end();) {
        if (*it < limit) {
            it = values.erase(it);
            ++removed;
        } else {
            ++it;
        }
    }
    return removed;
}

int main() {
    std::vector<int> values{10, 5, 25, 12, 15};
    std::cout << "contains 25: " << (contains(values, 25) ? "yes" : "no") << "\n";
    std::cout << "contains 99: " << (contains(values, 99) ? "yes" : "no") << "\n";
    std::cout << "empty contains 25: " << (contains({}, 25) ? "yes" : "no") << "\n";
    const auto removed = remove_below(values, 15);
    assert(removed == 3 && (values == std::vector<int>{25, 15}));
    std::cout << "removed " << removed << ", left:";
    for (int value : values) { std::cout << ' ' << value; }
    std::cout << "\nRange checked\n";
    return 0;
}
Text
contains 25: yes
contains 99: no
empty contains 25: no
removed 3, left: 25 15
Range checked

For the empty vector, begin() == end(), so std::find returns end() without reading anything and contains is false. In remove_below, each erase hands back a valid iterator to the next element, so the 5 that slides into the 10's place is still examined, and 15 stays because the test is < limit. The next lesson replaces the fixed is_short function with lambdas, which let you choose the limit when you call the algorithm.

Was this article helpful?

Your response is saved on this device.