In C++ I can use reverse_iterator
to loop elements of container, say, list
, backwards.
How do I iterate over a certain number of elements? Not reaching the beginning? This code works, but I feel there is a better way.
std::list<int> mylist{1,2,3,4,5};
int cnt = 3;
for (auto rit = mylist.rbegin(); rit != mylist.rend(); ++rit) {
if (cnt == 0) break;
std::cout << *rit << " ";
--cnt;
}
Expected output {5, 4, 3}
.