STL Algorithms

sort, find, transform, etc.

Interview Relevant: Efficient operations

STL Algorithms

Generic algorithms that work with iterators.

Code Examples

Essential STL algorithms.

cpp
1#include <algorithm>
2#include <numeric>
3
4vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};
5
6// Sorting
7sort(v.begin(), v.end());                    // Ascending
8sort(v.begin(), v.end(), greater<int>());    // Descending
9partial_sort(v.begin(), v.begin()+3, v.end()); // Top 3
10nth_element(v.begin(), v.begin()+3, v.end());  // Kth element
11
12// Searching
13auto it = find(v.begin(), v.end(), 5);
14auto it2 = find_if(v.begin(), v.end(), [](int x) { return x > 4; });
15bool found = binary_search(v.begin(), v.end(), 5);  // Sorted only!
16auto lb = lower_bound(v.begin(), v.end(), 4);
17auto ub = upper_bound(v.begin(), v.end(), 4);
18
19// Counting
20int cnt = count(v.begin(), v.end(), 1);
21int cnt2 = count_if(v.begin(), v.end(), [](int x) { return x > 3; });
22
23// Transforming
24transform(v.begin(), v.end(), v.begin(), [](int x) { return x * 2; });
25replace(v.begin(), v.end(), 1, 10);
26reverse(v.begin(), v.end());
27rotate(v.begin(), v.begin()+3, v.end());
28
29// Aggregation
30int sum = accumulate(v.begin(), v.end(), 0);
31int product = accumulate(v.begin(), v.end(), 1, multiplies<int>());
32auto [minIt, maxIt] = minmax_element(v.begin(), v.end());

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In