I just saw some C++ code like this. It was using a condition to decide whether to walk forward or backward through a std::vector
. The compiler doesn\'t complain, b
I can't speak to how safe that code is but I think it's a pretty poor style. A better way would be to use iterators which support forward or reverse iteration.
For example:
std::vector v = { 1, 2, 3, 4, 5 };
bool rev = true;
if (rev)
{
for (auto itr = v.rbegin(); itr != v.rend(); ++itr)
{
std::cout << *itr << "\n";
}
}
else
{
for (auto itr = v.begin(); itr != v.end(); ++itr)
{
std::cout << *itr << "\n";
}
}