问题描述
我需要获得一个基于偏移量的迭代器。
即具有开始的迭代器:
auto it = set.begin()
我需要转到偏移量为ofst
的迭代器:
it + ofst
有没有办法做到这一点?我需要增量it++
迭代器ofst
倍。
解决方法
我需要到达偏移量为
ofst
:it + ofst
的迭代器: 一种方法吗?
否,没有为此operator+
定义std::set::iterator
重载(又名双向迭代器)。但是,您可以按照以下方式使用std::next
标头中的<iterator>
来实现相同的目标。
#include <iterator> // std::next
auto nthIter = std::next(it,ofst);
这在幕后基本上也增加了ofst
倍。
std::set
有bidirectional iterators,没有random access iterators这样的奢侈品,因此需要像这样递增。
话虽如此,您可以为双向迭代器which will not be recommended though重载operator+
(甚至是operator-
)。