如何基于set.begin的偏移量迭代std :: set?

问题描述

我需要获得一个基于偏移量的迭代器。

即具有开始的迭代器:

auto it = set.begin()

我需要转到偏移量为ofst的迭代器:

it + ofst

有没有办法做到这一点?我需要增量it++迭代器ofst倍。

解决方法

我需要到达偏移量为ofstit + ofst的迭代器: 一种方法吗?

否,没有为此operator+定义std::set::iterator重载(又名双向迭代器)。但是,您可以按照以下方式使用std::next标头中的<iterator>来实现相同的目标。

#include <iterator>  // std::next

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

这在幕后基本上也增加了ofst倍。

std::setbidirectional iterators,没有random access iterators这样的奢侈品,因此需要像这样递增。


话虽如此,您可以为双向迭代器which will not be recommended though重载operator+(甚至是operator-)。