-
for, while with Vectors
My question is this, why would I prefer one over the other ?
Code:
vector<int> v(10);
vector<int>::iterator p;
int i = 0;
p = v.begin();
while( p != v.end() ) {
*p = i;
cout << *p << " ";
p++;
i++;
}
versus this.
Code:
vector<int>v(10);
vector<int>::iterator p;
int i = 0;
for( p = v.begin(); p != v.end(); p++ ) {
*p = i;
cout << *p << " ";
i++;
}
Is it best to use a while loop when dealing with containers?
-
The second is clearer, that's why you would prefer it. It's what the for-loop is for, after all. You have initialization, condition and incrementation all in one place, instead of three places like with the while-loop.
-
So synaticly both versions do the same thing on the container vector? I was'nt sure if the for loop had some upredictable side effect. The book Im going through right now( STL programing from the ground up ) uses the while loop to intialize the vector and display the contents. It also demonstrates the for loop but not with iterators. It indexes them like an array.
thanks for the reply!
-
To simplify this difficult decision, it is recommended to use the for_each algorithm instead of user written loops. ;) ;)
mfg JJ
-
Ya i seen that too.
Code:
for_each( v.begin(), v.end(), show )
That is next
I was just curious about why the while loop was used so much in the book im reading through...so i thought maybe there was a good reason for it.
-
No, I think that's mainly the author's preference (and a stupid one at that...).