0

is there any difference between running over a vector using [], like this:

vector<ClassName*> my_vec(10);
int N = 10;

for (int i =0; i<N; i++){
   cout<<my_vec[i];
}

or, using iterators, like this:

for(std::vector<ClassName*>::iterator it = my_vec.begin(); it != my_vec.end(); it++) {
            cout<< (*it);
}

except the fact that we neet to keep an updated variable to hold vector size?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Day_Dreamer
  • 3,311
  • 7
  • 34
  • 61
  • You don't have to keep a variable to hold the vector size. It tracks its own size, which you can retrieve with `my_vec.size()`. – Benjamin Lindley Jan 05 '15 at 17:48
  • You dont need a variable in either case, you can just call `my_vec.size()` – Borgleader Jan 05 '15 at 17:48
  • You do not need (and should not use!) an extra size-variable! Use `std::vector::size` instead. – Baum mit Augen Jan 05 '15 at 17:48
  • This SO post is having good answers about this http://stackoverflow.com/questions/919406/what-is-the-difference-between-accesing-vector-elements-using-an-iterator-vs-an – Ankur Jan 05 '15 at 17:51
  • Simply use for range: `for (ClassName* className : my_vec) {...}` (you may also use `auto`) – Jarod42 Jan 05 '15 at 17:52
  • For vectors there's not much difference as both indexing and iterators are random-access. For other data structures, such as lists, you cannot use operator [] – Neil Kirk Jan 05 '15 at 17:53
  • The first code is error prone. You hardcode `10` in the declaration of the vector, then introduce an int variable that has `10`. There are too many moving parts that can go wrong. The second code guarantees you iterate over valid entries in the vector. – PaulMcKenzie Jan 05 '15 at 17:55

0 Answers0