1

As the title states. Presume we have a container like std::vector c and want to use the iterators.

As example should I prefer writing:

std::accumulate( c.begin(), c.end(), 0 );

or

std::accumulate( begin( c ), end( c ), 0 ); 

Which case is preferable and why? Are there special cases which only one type can handle or are they always interchangeable?

Taron
  • 1,205
  • 2
  • 13
  • 29
  • Do you meant `std::begin(c)`? In generic code this is safer, although I've found in practice it doesn't really matter. – AndyG Jun 20 '19 at 19:19
  • @Incubbus you are right this is a duplicate. I did not find it though. Thanks for pointing this out – Taron Jun 20 '19 at 19:21
  • 3
    @AndyG You only need `std::` if you are dealing with an array. Every other standard container will find the right `begin` and `end` due to ADL. In generic code, you are arguably better off using `begin` so that it will correctly find the free `begin` functions that other types might provide (which won't be in `std`) and having `using std::begin;` to work with arrays. – François Andrieux Jun 20 '19 at 19:23
  • 2
    @Taron If you know `c` is an `std::vector` then is doesn't really matter. It really only matters in a generic context, where `c` is just *some container*, like in the case where `c`'s type depends on a template argument or if you expect `c`'s type to possibly change in the future. – François Andrieux Jun 20 '19 at 19:26

0 Answers0