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?