Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the better way to write iterators for a loop in C++

For a very simple thing, like for example to print each element in a vector, what is the better way to use in C++?

I have been using this:

for (vector<int>::iterator i = values.begin(); i != values.end(); ++i)

before, but in one of the Boost::filesystem examples I have seen this way:

for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it)

For me it looks more complicated and I don't understand why is it better then the one I have been using.

Can you tell me why is this version better? Or it doesn't matter for simple things like printing elements of a vector?

Does i != values.end() make the iterating slower?

Or is it const_iterator vs iterator? Is const_iterator faster in a loop like this?

like image 441
hyperknot Avatar asked Jul 12 '11 22:07

hyperknot


1 Answers

  1. Foo x = y; and Foo x(y); are equivalent, so use whichever you prefer.

  2. Hoisting the end out of the loop may or may not be something the compiler would do anyway, in any event, it makes it explicit that the container end isn't changing.

  3. Use const-iterators if you aren't going to modify the elements, because that's what they mean.

for (MyVec::const_iterator it = v.begin(), end = v.end(); it != end; ++it)
{
  /* ... */
}

In C++0x, use auto+cbegin():

for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)

(Perhaps you'd like to use a ready-made container pretty-printer?)

like image 52
Kerrek SB Avatar answered Nov 07 '22 13:11

Kerrek SB