Re: Variables in for loop (style issue)
Bob Hairgrove wrote:
> On 6 May 2006 10:21:43 -0400, "kanze" <kanze@gabi-soft.fr> wrote:
>> Bob Hairgrove wrote:
>>
>> [...]
>>> One big problem is the fact that not all containers are
>>> vectors, and calling size() is very inefficient for almost
>>> all containers except for std::vector.
>> Is it? His code in the loop said "do something with v[i]".
>> What container supports v[i], and has an inefficient size()
>> function.
> Good point. I suppose they go hand in hand. My concerns here
> were guided by what Scott Meyers says in "Effective STL" where
> he recommends testing "if (v.empty())" instead of "if
> (v.size())" where v can be a variable of just about any STL
> container type.
Well, a perhaps more telling argument for using v.empty()
instead of v.size() != 0 is that it says more explicitly what
you are testing for.
>>> How about this:
>>> for (size_t i=0, std::vector<whatever_v_is>::iterator it = v.begin();
>>> it != v.end(); ++i, ++it) {
>>> // etc.
>>> }
>>> I think this solves all the above problems nicely.
>> But introduces a new one: it's not legal C++, and won't
>> compile.
> Oops ... so we declare i outside of the loop, then it should
> work (or did you see anything else wrong with it?)
Why i, and not it? For that matter, why use two variables, when
one will do the trick?
--
James Kanze kanze.james@neuf.fr
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! ]