Tuesday, 15 February 2011

c++ - Using a function as the second argument of a 'for' loop -



c++ - Using a function as the second argument of a 'for' loop -

this question has reply here:

should iterate vector iterator or access operator? 4 answers

let's assume have next code:

for(std::vector<int>::iterator = vect.begin(); != vect.end(); ++i) { //do smth here }

is vect.end() going re-called each iteration? if yes, how should iterate vector then?

having function called within logical look (second argument of loop) bad practice?

yes, will. however, if compiler can determine value returned vect.end() never change, of course of study optimize out. however, if want avoid doing sure, alter code to:

for(std::vector<int>::iterator = vect.begin(), end = vect.end(); != end; ++i) { //do smth here }

you should, of course, create sure code doesn't rely on end() beingness checked on every iteration. example, if doing vect.erase(i) on elements in vector, need create sure got new end() iterator every time (and create sure assign result of erase i).

c++

No comments:

Post a Comment