mardi 23 octobre 2012

why you should prefer std::algorithm...

Today i worked on a huge legacy code base when i meet (1x more) the following kind of loop:


std::vector<int> vec;
...
int max_value = 0;
for ( int i=0 ; i<(int)vec.size() ; i++ )
  {
    if (vec[i] > max_value)
    {
      max_value = vec[i];
    }
  }

I was wondering why some developer always try to reinvent the wheel ?

C++ comes with a tons of useful algorithm to do that kind of stuff, and with an explicit name. In example that code can be rewrite with:


#include <algorithm>
...
std::vector<int> vec;
...
int max_value = *std::max_element<std::vector<int>::iterator >(vec.begin(), vec.end());

it's shorter and more explicit...

Note for C++11 users:



auto max_value = *std::max_element<std::vector<int>::iterator >(begin(vec), end(vec));

2 commentaires :

  1. I still find it very verbose and not easily readable. What I would like is this:

    using std;
    int max_value = max_element(vec);

    RépondreSupprimer
  2. Yes
    but for the "using std;" clause, i never use it because i prefer see exactly from which lib/component functions come.

    I have several visitor/day but since i wrote some tips in that blog, it's the 1st comment i receive :)! Thank you!

    RépondreSupprimer