Learning pathOriginal reference
Lesson 4 of 12

Algorithms over a range

Sort, reverse, search, sum, remove, and deduplicate with the right return types and costs.

Free algorithms receive iterators

std::sort(v.begin(), v.end()) orders integer elements nondecreasingly and modifies the vector. A vector has no sort() member. Sorting preserves duplicates. std::reverse changes order but does not sort an arbitrary sequence.

Sorting n integers needs O(n log n) comparisons for nontrivial sizes. Reversal takes a linear number of swaps. A comparison involving long strings can cost more than an integer comparison, so include the element cost when appropriate.

A search returns a position; a sum needs a type

std::find scans an unsorted or sorted range and returns the first matching iterator, or the supplied last iterator if absent. Compare to end() before dereferencing. For a vector, subtracting begin() from a valid returned iterator gives its zero-based index.

std::accumulate starts with the initial value you supply. Use 0LL for a long long accumulator. Assigning accumulate(..., 0) into a long long variable does not widen additions that already happened in int. An empty range returns the initial value.

C++23
// Complete C++23 program. No input; output: 1 17
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
    std::vector<int> values{5, 7, 7, -2};
    auto it = std::find(values.begin(), values.end(), 7);
    if (it == values.end()) std::cout << -1;
    else std::cout << (it - values.begin());
    std::cout << ' ' << std::accumulate(values.begin(), values.end(), 0LL)
              << '\n';
}

Optional: erase all matches, then deduplicate

The free function std::erase(values, target), declared for vectors in <vector>, removes every matching value and returns the number removed. It differs from the member values.erase(iterator), which removes one position.

std::unique compacts consecutive equal values and returns a new logical end; it does not shrink the vector. Sort first if all equal values should become adjacent, then erase the tail. Without sorting, 1 2 1 has no adjacent duplicate and remains unchanged. Sorting changes original order, so only use this when that is acceptable.

Container workbench

Insert values, then remove the next accessible item. Priority queue values are shown sorted for explanation, not as an internal heap.

80
31
52

Next removal: 5. Size: 3.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

After unique on the sorted vector 2 2 5 5 5, what is size() before erasing the tail?

Choose an answer
Try it yourself

Turn the idea into code

Read n, a target, and n integers. Remove every target value, print the number removed, then print the remaining distinct values in ascending order. Use C++23 library operations and handle an empty result.

Give me a hint

std::erase removes target matches. Then sort, unique, and erase the tail after the returned iterator.

Show the explained solution

Removing matches is linear. Sorting groups duplicate values; unique keeps one in its logical prefix and the final erase changes the actual size. Overall time is O(1 + n log(n + 1)); stored input is O(n + 1), plus sorting implementation workspace.

C++23
// Complete C++23 program. Input: 0 <= n <= 200000, target, then n integers.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
    int n = 0, target = 0;
    std::cin >> n >> target;
    std::vector<int> values(n);
    for (int& x : values) std::cin >> x;
    std::cout << std::erase(values, target) << '\n';
    std::sort(values.begin(), values.end());
    auto newEnd = std::unique(values.begin(), values.end());
    values.erase(newEnd, values.end());
    for (int i = 0; i < static_cast<int>(values.size()); ++i) {
        if (i != 0) std::cout << ' ';
        std::cout << values[i];
    }
    std::cout << '\n';
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.