Re: iterator and index
Daniel K. O. wrote:
G escreveu:
And whether is "vi.end()" called when each loop happens?
Yes, it is "called" each time, as this is part of the semantics of the
for command.
And if I change the code of iterator to:
vector<int>::iterator x=vi.end();
for(vector<int>::iterator iter=vi.begin(); iter!=x;
++i)
will it take less time?
Not in every (relevant) implementation I have seen so far, unless you
disable optimizations. The .end() member in containers usually consists
of a single return statement available in the header, that gets inlined
easily. Try looking at the generated assembly, and see it for yourself;
the output will be almost (when not completely) identical.
Have you actually measured it? The measurements I did (on one
particular compiler, on one particular machine) showed that it
did make a difference. Not a large difference. Not something
that I would normally worry about, unless the profiler said I
had to. But something measurably large if the loop was
otherwise trivial.
I didn't look at the assembler to determine why there was a
difference, but I suspect that because the pointer was part of
an object (the vector) which was generally accessible, the
compiler was unable to determine that it never varied, and so
re-read it from memory each pass through the loop. Where as if
the pointer is a local variable whose address is never taken,
the compiler automatically knows that it sees all modifications,
and that if it doesn't see any, it can keep the variable in
memory.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]