C++
I have the following iteration loop:
for (it = container.begin(); it != container.end(); ++it) {
//my code here
}
I want to end this iteration 1 element early. I've tried the following but it doesn't compile:
for (it = container.begin(); it != container.end() - 1; ++it) { //subtract 1
//my code here
}
How can this be done? Thanks.
You can iterate up to one before std::prev(s.end())
where s
is your set, taking care of the possibility that the container is empty:
#include <iterator> // for std::prev
auto first = s.begin();
auto last = s.empty() ? s.end() : std::prev(s.end()); // in case s is empty
for (auto it = first; it != last; ++it) { ... }
Note: std::prev
requires C++11 support. A C++03 alternative is --s.end()
.
Try std::prev
:
for (it = container.begin(); it != std::prev(container.end()); ++it) { //subtract 1
//my code here
}
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