Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

This is the answer of exercise #7: AddOne.

## Question #0: How many correct ways are there to do this?

The answer is a product of the number of ways to add one to an int and the number of ways to iterate through a std::vector.

The number of ways to add one to an int are five:

- Assignment 1st (x=1+x)
- Assignment 2nd (x=x+1)
- Increase (x+=1)
- Post-increment (x++)
- Pre-increment (++x)

The number of ways to iterate through a std::vector are twelve:

- Using a for-loop, requesting the std::vector its size only once
- Using a for-loop, requesting the std::vector its size every iteration
- Using an iterator, requesting the std::vector its end only once
- Using an iterator, requesting the std::vector its end only every iteration
- Using an algorithm to a non-inlined function
- Using an algorithm to an inlined function
- Using an algorithm to a functor with a non-inlined operator()
- Using an algorithm to a functor with an inlined operator()
- Using BOOST_FOREACH
- Using the Boost Lambda library
- Using the C++11 its ranged for-loop
- Using the C++11 lambda expressions

This makes the number of ways to do this sixty!

There are two more:

- Using an algorithm to std::plus using std::bind1st
- Using an algorithm to std::plus using std::bind2nd

Total: there are sixty-two ways to add one to each element in a std::vector!

P.S. an additional way (though beyond this exercise) is to use assembler.

## Question #1: Write a program that tests which way is fastest

This kind of program is called a benchmark.

There are too many ways to write one, so I'll just show you mine, which can be found at
the cpp_benchmark_add_one GitHub.
There you will find the benchmark results in the Travis CI scripts.

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.