Skip to content

Latest commit

 

History

History
149 lines (99 loc) · 3.69 KB

CppExerciseAddOneAnswer.md

File metadata and controls

149 lines (99 loc) · 3.69 KB

 

 

 

 

 

 

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:

 

  1. Assignment 1st (x=1+x)
  2. Assignment 2nd (x=x+1)
  3. Increase (x+=1)
  4. Post-increment (x++)
  5. Pre-increment (++x)

 

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

 

  1. C++98C++11STL Using a for-loop, requesting the std::vector its size only once
  2. C++98C++11STL Using a for-loop, requesting the std::vector its size every iteration
  3. C++98C++11STL Using an iterator, requesting the std::vector its end only once
  4. C++98C++11STL Using an iterator, requesting the std::vector its end only every iteration
  5. C++98C++11STL Using an algorithm to a non-inlined function
  6. C++98C++11STL Using an algorithm to an inlined function
  7. C++98C++11STL Using an algorithm to a functor with a non-inlined operator()
  8. C++98C++11STL Using an algorithm to a functor with an inlined operator()
  9. C++98C++11Boost Using BOOST_FOREACH
  10. C++98C++11Boost Using the Boost Lambda library
  11.  C++11STL Using the C++11 its ranged for-loop
  12.  C++11STL Using the C++11 lambda expressions

 

This makes the number of ways to do this sixty!

 

There are two more:

 

  1. Using an algorithm to std::plus using std::bind1st
  2. 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.