Learning Hub Search Ctrl K

Legacy C++ › 6. The Standard Template Library

Algorithms

sort, find, transform, accumulate and the erase-remove idiom.

intermediate #stl#algorithms#sort#find#transform#accumulate#erase-remove

Explanation

<algorithm> and <numeric> provide about 80 generic functions that work on iterator ranges. Prefer them over hand-written loops: they state intent, are well tested, and are often faster.

Group Functions
Search find, find_if, count, binary_search, lower_bound
Sort sort, stable_sort, partial_sort, nth_element
Modify copy, transform, replace, fill, reverse, rotate, unique
Remove remove, remove_if (do not shrink the container!)
Numeric accumulate, inner_product, partial_sum
Compare equal, min_element, max_element, for_each

remove/remove_if just move the kept elements to the front and return the new logical end. To really delete, use the erase-remove idiom: v.erase(std::remove(v.begin(), v.end(), x), v.end());.

Binary searches (binary_search, lower_bound) require a sorted range.

Example

#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

bool isOdd(int x) { return x % 2 != 0; }
int  doubled(int x) { return x * 2; }

int main() {
    std::vector<int> v;
    int data[] = {5, 3, 8, 1, 9, 2};
    v.assign(data, data + 6);

    std::sort(v.begin(), v.end());                              // 1 2 3 5 8 9
    std::cout << std::binary_search(v.begin(), v.end(), 8) << "\n";

    std::vector<int>::iterator it = std::find(v.begin(), v.end(), 5);
    std::cout << "5 at index " << (it - v.begin()) << "\n";

    std::cout << "odd count: " << std::count_if(v.begin(), v.end(), isOdd) << "\n";

    std::vector<int> w(v.size());
    std::transform(v.begin(), v.end(), w.begin(), doubled);     // 2 4 6 10 16 18
    std::cout << "sum: " << std::accumulate(w.begin(), w.end(), 0) << "\n";

    v.erase(std::remove_if(v.begin(), v.end(), isOdd), v.end()); // erase-remove idiom
    std::cout << "evens: ";
    for (std::size_t i = 0; i < v.size(); ++i) std::cout << v[i] << " ";
    std::cout << "\n";

    std::vector<std::string> names;
    names.push_back("pear"); names.push_back("fig");
    std::reverse(names.begin(), names.end());
    std::cout << names[0] << "\n";
    return 0;
}

Common pitfalls

  • Calling remove and forgetting erase: the container keeps its size and the tail holds unspecified values.
  • binary_search on unsorted data gives wrong answers silently.
  • std::sort needs random-access iterators; use list::sort() for lists.
  • A comparator must be a strict weak ordering (<, never <=) or sort can crash.
  • Destination ranges (transform, copy) must be large enough or use an inserter.

Legacy vs modern

C++11 lambdas replace named predicates ([](int x){ return x % 2; }) and add all_of, any_of, none_of, copy_if, iota. C++17 adds parallel execution policies; C++20 std::ranges::sort(v) accepts the container directly. See Ranges and Views.

Exercises

1. Remove all elements equal to 0 from a vector<int> v.
v.erase(std::remove(v.begin(), v.end(), 0), v.end());