The <algorithm> and <numeric> headers offer over 100 highly optimized algorithms for data manipulation. Professional C++ developers adhere to the principle: "Know your algorithms and avoid writing manual raw loops."
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main() {
std::vector<int> data = {45, 12, 85, 32, 89, 39, 69, 44};
// 1. Sort in ascending order: O(N log N)
std::sort(data.begin(), data.end());
// 2. Binary search: O(log N)
bool found = std::binary_search(data.begin(), data.end(), 69);
std::cout << "69 found: " << std::boolalpha << found << "\n";
// 3. Accumulate sum: O(N)
int total = std::accumulate(data.begin(), data.end(), 0);
std::cout << "Total Sum: " << total << "\n";
// 4. Transform: Square every number
std::vector<int> squared(data.size());
std::transform(data.begin(), data.end(), squared.begin(), [](int n) {
return n * n;
});
return 0;
}
Boost your C++ proficiency by studying these closely connected core modules:
Passing iterator ranges (begin, end) to algorithms.
Writing inline predicate lambdas for algorithms.
Modern pipeline syntax for STL algorithms.