For efficiency reasons, I always avoid writing loops like this:
for(std::size_t i = 0; i < vec.size(); ++i) { ... }
where vec is an STL container. Instead, I either do
const std::size_t vec_size = vec.size();
for(std::size_t i = 0; i < vec_size; ++i) { ... }
or use the container iterators.
But how bad is the first solution really? I remember reading in Meyers that it will be quadratic instead of linear because the vector doesn’t know its size and repeatedly has to count. But won’t modern compilers detect this and optimize it away?
vector::size()is constant-time and usually implemented as a trivial inline function that is optimised away. Don’t bother hand-optimising it.