Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) Answer of exercise #7: AddOne

 

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:

 

In the zip file, the results of the profilers gprof and cachegrind are included as text files.

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict