If i have a myVector which is a STL vector and execute a loop like this:
for(int i=0;i<myVector.size();++i) { ... }
Does the C++ compiler play some trick to call size() only once, or it will be called size()+1 times?
I am little confused, can anyone help?
Logically,
myVector.size()will be called each time the loop is iterated – or at least the compiler must produce code as if it’s called each time.If the optimizer can determine that the size of the vector will not change in the body of the loop, it could hoist the call to
size()outside the loop. Note that usually,vector::size()is an inline that’s just a simple difference between pointers to the end and beginning of the vector (or something similar – maybe a simple load of a member that keeps track of the number of elements).So there’s actually probably little reason for concern about what happens for
vector::size().Note that
list::size()could be a different story – the C++03 standard permits it to be linear complexity (though I think this is rare, and the C++0x standard changeslist::size()requirements to be constant complexity).