2

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88
YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • 1
    [`std::next`](https://en.cppreference.com/w/cpp/iterator/next) but it basically has to increment n times for non contiguous containers such as `std::set`. – Jarod42 Aug 20 '20 at 08:17

1 Answers1

5

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.

JeJo
  • 30,635
  • 6
  • 49
  • 88