Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:
It really, really depends of what are you doing in the ...
code.
If the compiler can prove that vint.end()
is not going to change then it might not matter, but you are at the mercy of the compiler optimizations then and how clear is the ...
code.
Your approach is the one that helps the compiler the most, you are promising that the end
iterator will not be invalidated and that you are not going to modify the element in end
(which is invalid any way). You cannot be more explicit than this about what you promise you will do in ...
.
It is 2019, and for-range loops are basically equivalent to your code: https://en.cppreference.com/w/cpp/language/range-for
{
auto && __range = range_expression ;
auto __begin = begin_expr ;
auto __end = end_expr ;
for ( ; __begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
which incidentally means that if you were not really interested in it
, but in *it
, you can put an end (no pun intended) to the dilemma and just write:
std::vector vint;
for(auto&& e : vint)
{
.... // use `e` instead of `*it`.
}