0

This is more of a conceptual doubt. I am learning to use vectors in C++.

While iterating through a vector, I could do it in two ways:

vector<int> temp;
for (int j = 0; j < 10; j++){     
    temp.push_back(j);
}

int sum1 = 0;
int sum2 = 0;

//Method 1: almost treating it like an array
for (int i = 0; i < temp.size(); i++){
    sum1 = sum1 + temp[i];
}

//Method 2: using an iterator
vector<int>::iterator it;
for(it = temp.begin(); it < temp.end(); it++) {     
    sum2 = sum2 + *it;
}

Both methods worked fine and yielded expected results. However, I have noticed that most of the suggested codes (on stackexchange, etc) use iterators. Is there any specific reason for that or is it just out of convenience?

Nicky Noah
  • 21
  • 4

2 Answers2

0

Iterators are more generic. Using iterators you can use any class supporting iterators. If you use "method 1" then you're limited to vectors and std::array.

I would even go further and stop using container.begin() and container.end(), and instead use std::begin and std::end (if iterators are needed) or the range-based for loop.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

First option is preferred when size of the vector is small. Moreover, if you're not planning to use it to alter the contents of the vector, then why use it ? Use Iterator instead.

Read this for clarification. Why use iterators instead of array indices?

Community
  • 1
  • 1
san A
  • 177
  • 2
  • 13