Use the standard algorithms library
Sort and search collections with reusable, well-tested algorithms.
- Apply
std::sort,std::find, and iterator ranges.
The standard library separates algorithms from containers. Many algorithms accept a half-open iterator range [first, last): the first element is included and the end iterator is not. std::sort orders a mutable range, while std::find searches for a value and returns last when it is absent. Include <algorithm> and prefer standard algorithms over handwritten loops when they express the intent clearly.
1#include <algorithm>
2#include <iostream>
3#include <vector>
4
5int main() {
6 std::vector<int> values{7, 2, 5};
7 std::sort(values.begin(), values.end());
8 for (const auto& value : values) std::cout << value << " ";
9 std::cout << "\n";
10}2 5 7
Iterator invalidation rules depend on the container and operation. For example, appending to a vector may reallocate its storage and invalidate iterators, pointers, and references to its elements.
Key takeaways
Standard algorithms work over iterator ranges.
Remember ranges are half-open.
Be aware that container mutations may invalidate iterators.
Lesson quiz
5 questions · pass with 4 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write C++
Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.
Sort and print values
Read a count and that many integers, sort them in ascending order, and print them on one line separated by spaces.
- Unordered values
- Duplicates
Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…