Algorithms like std::sort, std::find, and std::transform take a pair of iterators (begin/end) marking a range, making them work identically across any container that provides compatible iterators — the same std::sort call works on a vector, a deque, or a plain array. Beyond genericity, using a standard algorithm instead of a hand-written loop is typically both safer (the standard library's implementation has been extensively tested) and more self-documenting (std::find_if immediately communicates intent, where an equivalent hand-rolled loop requires reading the whole body to understand).
sort and find: the essentials
The comparator lambda passed to sort controls the ordering directly, without needing a separate named comparison function for a one-off case.
std::vector<int> v = {5, 2, 8, 1, 9};
std::sort(v.begin(), v.end()); // ascending: 1 2 5 8 9
std::sort(v.begin(), v.end(), std::greater<>()); // descending: 9 8 5 2 1
auto it = std::find(v.begin(), v.end(), 8);
if (it != v.end()) {
std::cout << "found at index " << (it - v.begin()) << "\n";
}transform and accumulate: functional-style operations
transform applies a function to every element, writing results to a destination; accumulate folds a range down to a single value — both replace what would otherwise be a manual loop with explicit indexing.
std::vector<int> nums = {1, 2, 3, 4};
std::vector<int> doubled(nums.size());
std::transform(nums.begin(), nums.end(), doubled.begin(),
[](int n) { return n * 2; }); // doubled: 2 4 6 8
int sum = std::accumulate(nums.begin(), nums.end(), 0); // 10 — folds the range to one valuefind_if: searching by a condition, not an exact value
Unlike find (which needs an exact value to match), find_if takes a predicate — any lambda returning bool — letting the search condition be arbitrarily complex while the call itself stays readable.
std::vector<int> v = {3, 7, 12, 5, 20};
auto it = std::find_if(v.begin(), v.end(), [](int n) {
return n > 10; // find the first element satisfying an arbitrary condition
});
if (it != v.end()) {
std::cout << "first value over 10: " << *it << "\n"; // 12
}