Home > Enterprise >  Should I use for iterators instead of for range based loop, if so, why?
Should I use for iterators instead of for range based loop, if so, why?

Time:10-26

I just learned about iterators. Should I use this?

for (auto& i : just_a_vec )

Or this?

for (std::vector<std::string>::iterator it = just_a_vec.begin(); it < just_a_vec.end(); it  )

And if so, why this is the case?

CodePudding user response:

Iterators predate range-based for loops, so they used to be the only of these two alternatives available. Nowadays, range-based for has mostly replaced iterators when dealing with a simple loop.

However, iterators can be used in various other contexts as well. For example, you can do std::sort(v.begin(), std::next(v.begin(), 5)) to sort the first five elements of a vector while leaving the rest of it alone.

Going back to iterating over a whole container:

  • If you can accomplish what you want with a range-based for, then it leads to more legible code, so they are preferable by default.

  • If you need iterators for some reason, such as using an algorithm that requires them, or because you need to jump ahead or back while iterating, then use those instead.

Also: In the later case, you can/should still use auto when declaring the iterator:

for(auto it = just_a_vec.begin(); it < just_a_vec.end(); it  ) {
}

Edit: as asked: here's a simple, if a bit contrived, example where an iterator-based loop can still be useful:

// adds all values in the vector, but skips over twos values when encountering a 0
// e.g.: {1,2,0,4,5,2} => 5
int my_weird_accum(const std::vector<int>& data) {
  int result = 0; 
 
  for(auto it = data.begin(); it != data.end();   it) {
    auto v = *it;
    result  = v;

    if(v == 0) {
      // skip over the next two
      assert(std::distance(it, data.end()) > 2);
      std::advance(it, 2);
    }
  }
  return 0;
}

CodePudding user response:

Quick personal answer: Its somewhat sylistic and based on what version of c you are using. I typically prefer range based, but there are certainly moments iterators shine as well. Add both to your toolchest. For further reading.

Here is a list of other SO answers that get more into the performance and use cases.

For further information. Google

Range vs iterator loop c

  • Related