[LC++]STL Iterators and integers

Mark Phillips mark at austrics.com.au
Fri Aug 3 16:38:03 UTC 2001


Suppose I have a vector of strings:

vector<string> wiseSayings;

And I want to print them out, numbering each
saying.  I could do something like the following:

unsigned int i=0;
vector<string>::iterator it(wiseSayings.start());
for (; it<wiseSayings.end(); ++it, ++i)
  cout<<i<<": "<<*it<<endl;

Of course, seeing as I am using i anyway, I
could just do:

for (unsigned int i=0; i<wiseSayings.size(); ++i)
  cout<<i<<": "<<wiseSayings[i]<<endl;

which is much quicker to write, but
probably inefficient speed wise, because
the address of wiseSayings[i] needs to be
calculated at each step.  Unless of course
the compiler is smart enough to
optimize this away and turn it into the
previous form?? (Can gcc do this?)

But I am thinking that it should be possible
to use a third option, which would go
something like this:

for (vector<string>::iterator it(wiseSayings.start());
it<wiseSayings.end(); ++it)
  cout<<(unsigned int) it<<": "<<*it<<endl;

For this to work, the conversion (unsigned int) it
would need to extract an integral value, this
being the distance from wiseSayings.start() that
it has travelled.  Ie a count of the number of
increments applied to it.  Such a feature would
mean we could do away with defining a separate
count variable.

Is there some facility for doing something like
this with STL iterators?  Perhaps it would be
accessed via a member function, it.count() or
something.  I have not been able to find anything
like this and was wondering if some such
thing existed.

Cheers,

Mark.





More information about the tuxCPProgramming mailing list