Skip to content
Justice Tech School

Algorithms and Iterators

<algorithm> works on ranges given by iterators (begin and end). Common ones: sort, reverse, find, count, accumulate (in <numeric>), min_element and max_element. Combine them with lambdas for short, clear code.

Example
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

int main() {
  vector<int> v = {5, 2, 8, 1, 9, 4};
  sort(v.begin(), v.end(), greater<int>());
  for (int n : v) cout << n << " ";
  cout << endl;
  cout << accumulate(v.begin(), v.end(), 0) << endl;
  cout << *max_element(v.begin(), v.end()) << endl;
  cout << count_if(v.begin(), v.end(), [](int n) { return n % 2 == 0; }) << endl;
  auto it = find(v.begin(), v.end(), 8);
  cout << (it != v.end()) << endl;
}

Result

9 8 5 4 2 1 
29
9
3
1

Exercise

Sort a range.

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

Quiz Test

What does a pair of iterators describe?

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