Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end iteration through a C++ std::set one element early?

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.

like image 841
amorimluc Avatar asked Mar 22 '13 19:03

amorimluc


2 Answers

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().

like image 121
juanchopanza Avatar answered Sep 21 '22 01:09

juanchopanza


Try std::prev:

for (it = container.begin(); it != std::prev(container.end()); ++it) { //subtract 1
    //my code here
}
like image 45
Pubby Avatar answered Sep 18 '22 01:09

Pubby