[LC++]STL Iterators and integers

Grzegorz Mazur mazur at chemia.uj.edu.pl
Fri Aug 3 17:29:04 UTC 2001


Hey!

On Fri, 3 Aug 2001, Mark Phillips wrote:

> 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());
                                          ^^^^^^^
begin()?

> 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

Which basically means _one_ addition. Not that bad, compared to the total
number of instructions being executed in the loop. Especially I/O is
pretty expensive and will dominate the rest.

> the compiler is smart enough to
> optimize this away and turn it into the
> previous form?? (Can gcc do this?)

Can't really say, but in this case the difference shouldn't be large
enough to really justify any optimisation. Unless of course you've
profiled the code and found remarkable (or at least measureable)
differences.

> 
> 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());
                                               ^^^^^^^^
wiseSayings.begin()?

> 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.

Which would mean that everybody, even those who don't need such a feature,
would need to pay for it. So it's highly unlikely to be ever done.

> 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.

In case of vector, std::distance() should do. (It's quite efficient for
ramndom access iterators.) Anyway, the cost of calling distance, althougs
small, will be probably comparable to the cost of other solutions you've
considered. So I would strongly recommend using the simplest and most
clear approach with explicit index.

HTH,
-- 
Grzesiek




More information about the tuxCPProgramming mailing list