Vector Iteration

C++ vectors have many functions which allow element iteration.

Some of them are:

  • for_each
  • transform
  • copy_if
  • all_of
  • accumulate

To use for_each, transform, copy_if and all_of the package <algorithm> needs to be included.

To use accumulate the package <numeric> needs to be included.

for_each

Iterates the elements of a vector.

It accepts the following arguments:

  • start iterator
  • end iterator
  • function

Let's look at the following example:

Output:

The code snippet prints all values of the vector in a way specified in the printNumber function.



There is another way to specify the function argument like this:

Output:

This way we don't have to define a separate function in the global scope.



Certain elements can also be skipped from iteration using the iterators parameters.

Example:

Output:

In this case numbers.begin() + 2 skips the first 2 elements of the vector - 4 and 8.

numbers.end() - 1 skips the last element of the vector - 3.

So the only iterated elements are 7 and 6.

transform

Modifies vector's elements in a way returned by the function argument.

It accepts the following arguments:

  • start iterator of the iterated vector
  • end iterator of the iterated vector
  • start iterator of the vector which elements will be modified.
  • function

Output:

In this case, the modification is specified according to the returned value - value * 2.

copy_if

Allows filtering specific elements.

If the function argument returns true, the element will be present.

If the function argument returns false, it will not be present.

Output:

In order to access the filtered vector elements the back_inserter function is used to set their values in a separate vector.

all_of

Allows checking if all elements match a certain condition.

If all of the elements match the condition specified in the function argument, then the all_of function returns true. Otherwise, it returns false.

Output:

accumulate

Accumulates a single value based on the function argument.

It has 4 arguments:

  • start iterator
  • end iterator
  • initial value
  • function

Output:

The value returned by the accumulate function is based on the return statement of the function argument.

value is the iterated element - 1, 2, 3, 4, 5