Hello,
I've been reading Narue's Timesaving Tips and found this code from Dave Sinkula
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5};
vector<int> v(a, a + 5);
vector<int>::const_iterator it, end = v.end();
for (it = v.begin(); it < end; ++it)
{
cout << *it << endl;
}
}
This line is interesting:
for (it = v.begin(); it < end; ++it)
This works for vectors, but generally it's a bad programmer practice to use
relation operator < with iterators because it won't work with all containers.
Operator < is provided for random access iterators so this will not work with list
container.
I think, in order to write generic code, it's better practice to get used to uniform
approach in for different kind of containers and that's:
for (it = v.begin(); it != end; ++it)
And BTW, there is no need to include header <iterator> in this case since iterator class
is nested in vector class.
So, finally, this code example is:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int a[] = {1,2,3,4,5};
vector<int> v(a, a + 5);
vector<int>::const_iterator it, end = v.end();
for (it = v.begin(); it != end; ++it)
{
cout << *it << endl;
}
}
A small bonus:
Did you notice that some programmers use this form of for loop:
int i;
for ( i = 0; i < 10; i++ )
/*do something*/
when i is int,
and this form:
for ( i = v.begin (); i != v.end (); ++i )
/*do something*/
when i is an iterator?
Notice prefix and postfix ++i and i++. Are these forms same when using in loops?
Answer is depends on what counter i is. If i is an integer then there is no difference,
but if i is iterator, then there could be difference. As you probably know iterator is
often an object i.e. instance of a class and in that case there is difference whether using
i++ or ++i form.
Look at this small example (clasical implementation of operator ++=:
class Integer
{
int x;
public:
Integer ( int i ) : x ( i ) { };
Integer& operator ++ () //prefix
{
x++;
return *this;
}
Integer operator ++ (int) //postfix
{
return Integer ( x++ );
}
};
As you can see postfix version include creation of new object so we can conclude
that prefix form is faster.
If this issue is discussed before, I apologize but it's good to know.
- Micko