amorimluc
amorimluc

Reputation: 1719

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.

Upvotes: 9

Views: 9484

Answers (5)

Varun Garg
Varun Garg

Reputation: 2654

A c++98 solution to find last iterator can be

set.find(*set.rbegin())

Another option though it is undocumented and not recommended by people

it!= --set.end()

Also works, its behavior should be undefined when set is empty (begin == end)

Upvotes: 0

Pubby
Pubby

Reputation: 53097

Try std::prev:

for (it = container.begin(); it != std::prev(container.end()); ++it) { //subtract 1
    //my code here
}

Upvotes: 2

bames53
bames53

Reputation: 88225

result->container.end() - 1 requires a random access iterator, but you only have a bidirectional iterator. Instead you probably want --result->container.end().

Also you may not want to recompute that every time, although it's not a big deal:

for (auto i(begin(result->container)), e(--end(result->container)); i!=e; ++i) {

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227578

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

Upvotes: 15

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

for (it = container.begin(); it != --result->container.end(); ++it) { //subtract 1
    //my code here
}

std::set::iterator is bidirectional, which means you can do -- and ++ on it. It doesn't meet the requirements for a random access iterator, however, so you can't do - and + with it.

Upvotes: 0

Related Questions