WeCodeAcademy

C++ Iterators and Algorithms

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

int main() {
  vector<int> v = {5, 3, 8, 1, 9, 2};
  sort(v.begin(), v.end());
  for (int x : v) cout << x << " ";
  cout << endl;

  cout << binary_search(v.begin(), v.end(), 8) << endl;
  auto it = find(v.begin(), v.end(), 9);
  cout << distance(v.begin(), it) << 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 > 3; }) << endl;

  reverse(v.begin(), v.end());
  cout << v.front() << " " << v.back() << endl;

  vector<int> squares(v.size());
  transform(v.begin(), v.end(), squares.begin(), [](int n) { return n * n; });
  for (int x : squares) cout << x << " ";
  cout << endl;
  return 0;
}
Output
1 2 3 5 8 9 
1
5
28
9
3
9 1
81 64 25 9 4 1

Algorithms such as sort, find and accumulate work on iterator ranges, so the same code handles vectors, arrays and other containers.

Quick check

What do begin() and end() give you?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.