How to iterate std::set based on offset from set.begin()?

Viewed 268

I need to get an iterator based on offset.

i.e. having the iterator for begin :

auto it = set.begin()

I need to get to the iterator having offset ofst:

it + ofst

Is there a way to do that? of I need incremental increase it++ the iterator ofst times.

1 Answers

I need to get to the iterator having offset ofst: it + ofst: is there a way to do that?

No, there is no operator+ overload defined for this for std::set::iterator (aka bidirectional iterators). However, you can use std::next, from <iterator> header as follows to achive the same.

#include <iterator>  // std::next

auto nthIter = std::next(it, ofst);

This basically behind the scene increments ofst times too.

The std::set has bidirectional iterators, which has no luxuries like random access iterators, and hence need to increment like this.


That being said, you could overload the operator+(and maybe operator-) for the bidirectional iterators, which will not be recommended though.

Related