Basic C++ Algorithms: Sorting, Searching, and Generating
Harness the power of the <algorithm> library. A guide to std::sort, std::find, std::copy, and sequence generation.
Standard STL Algorithms
Instead of writing your own loops, C++ offers optimized algorithms in the <algorithm> and <numeric> headers. Here are four key categories:
1. Sorting
The most common function is std::sort, which operates in time.
std::vector<int> v = {5, 2, 8, 1, 9};
std::sort(v.begin(), v.end()); // Sorts in ascending order2. Searching
std::find: Searches for an element in any container (linear complexity).std::binary_search: Very fast searching in sorted data.
auto it = std::find(v.begin(), v.end(), 8);
if (it != v.end()) { /* Found! */ }3. Copying
std::copy allows moving data from one location to another. Often used with std::back_inserter.
std::vector<int> v2;
std::copy(v.begin(), v.end(), std::back_inserter(v2));4. Sequence Generation and Filling
std::fill: Fills a range with a single value.std::iota: (from<numeric>header) Generates a sequence of increasing numbers (e.g., 1, 2, 3...).
std::vector<int> data(10);
std::iota(data.begin(), data.end(), 1); // Fills from 1 to 10Best Practice: Prefer algorithms over manual
forloops. They are better optimized by the compiler and less prone to off-by-one errors.
You might also like
C-Style Strings: Char Arrays and Null Termination
Understanding low-level text handling: how character arrays terminated by a null byte work.
The <cmath> Library in C++ – Math Essentials
An overview of essential math functions in C++: from powers and roots to advanced trigonometry.
Understanding the #include Directive in C++
A guide to the #include directive: learn how the preprocessor links files and why the choice of brackets matters.