Skip to main content

11.4) Applying Algorithms To Arrays


int x[5] = {1, 4, 9, 16, 25};
reverse(x, x + 5);                   // x now 25, 16, 9, 4, 1
sort(x, x + 3);                      // x now 9, 16, 25, 4, 1
int sum = accumulate(x, x + 5, 0);   // sums values in x
  • Functions from the algorithms library work with arrays as well as containers and strings
  • Instead of supplying iterators to specify a range of elements, we use pointers; for an array x of size N, using x and x+N as pointers will ensure that the entire array is processed
  • See arrayalg.cpp for a complete example