|
-
November 29th, 2012, 12:32 AM
#2
Re: Vector iterators
 Originally Posted by raptor88
C++ beginner learning how to use vectors.
I see that there are 3 ways to iterate through a vector.
Code:
Method 1:
for(vector<int>::iterator it = myVect.begin(); it != myVect.end(); it++)
cout << *it << ' ';
Method 2:
for (vector<int>::size_type i = 0; i < myVect.size(); i++)
cout << myVect[i] << ' ';
Method3:
for (unsigned i = 0; i < myVect.size(); i++)
cout << myVect[i] << ' ';
If my craps program will:
- only ever use the same vector container,
- will have a maximum of 50 elements,
- will only ever be compiled using VC++ 2010 Express,
can I just use method-3 safely? If not, why not?
And actually, with only 50 elements max, couldn't I use "int i = 0" in the for statement instead of unsigned?
Just trying to understand it all.
Thanks,
Raptor
Your mistake is assuming that you know the future.
Write the code once so that regardless of what your future plans are, the code will compile without error or warning or have run time issues. No good programmer says "I'm using such-and-such compiler, have only n items now,.." etc., and then writes code that reflects that. They write the code once, and regardless of whatever happens a month, a year, two years, etc. down the road, the code still works.
Secondly, there are other ways to iterate through a vector or any other container. One of these ways is to use the for_each() algorithm function. Using that function would have used the more efficient pre-increment instead of the less efficient post-increment of the iterator in your first example:
Code:
for(vector<int>::iterator it = myVect.begin(); it != myVect.end(); ++it)
cout << *it << ' ';
Note the change to pre-increment. However the for_each() would have automatically corrected that instead of you having to do it.
Also, if your goal is to just use cout in a loop, a std::copy is all you need:
Code:
#include <algorithm>
#include <iostream>
#include <iterator>
//...
std::copy(myVect.begin(), myVect.end(), std::ostream_iterator<int>(std::cout, " "));
Regards,
Paul McKenzie
Last edited by Paul McKenzie; November 29th, 2012 at 12:40 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|