Skip to content
Justice Tech School

More STL Algorithms

<algorithm> offers sort, find, count_if, transform, accumulate, remove_if, unique, reverse, max_element, binary_search and more. Combine with lambdas.

Example
vector<int> v = {5, 2, 8, 1, 9, 3};
sort(v.begin(), v.end());
auto it = lower_bound(v.begin(), v.end(), 5);
cout << *it << " " << count_if(v.begin(), v.end(), [](int x) { return x > 3; }) << "\n";
vector<int> sq(v.size());
transform(v.begin(), v.end(), sq.begin(), [](int x) { return x * x; });
cout << accumulate(sq.begin(), sq.end(), 0) << " " << *max_element(v.begin(), v.end()) << "\n";
v.erase(remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());
for (int x : v) cout << x << " ";
cout << "\n";

Result

5 3
184 9
1 3 5 9 

Exercise

Sort a range.

(v.begin(), v.end())

Quiz Test

Which counts items matching a test?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.