I have got a (stupid?) C / C++ question about a loop:
for (size_t i = 0; i < std::distance(begin, end); ++i) {
a.push_back(i);
}
begin and end are two iterator. My question is, is std::distance(begin, end) calculated for each element in the loop? Or is it better to use this version:
size_t dist = std::distance(begin, end);
for (size_t i = 0; i < dist; ++i) {
a.push_back(i);
}
Second version is better. In the first one the condition is evaluated each time (no automatic asumption about the result being invariant).
Yes. The second version is better.
As for the first version, if the container type a is std::vector, and begin and end are iterators of a, then the push_back operation might cause resizing the vector, which in turn will invalidate begin and end iterators, and using them to calculate the distance in the next iteration will invoke undefined behaviour. In this case, the second is not only better, it is well-defined as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With