我需要获取一个基于偏移量的迭代器。
即具有 begin 的迭代器:
auto it = set.begin()
我需要到达具有偏移量ofst
的迭代器:
it + ofst
有办法做到这一点吗?我需要增量增加 it++
迭代器 ofst
次。
最佳答案
I need to get to the iterator having offset
ofst
:it + ofst
: is there a way to do that?
不,没有operator+
为此定义的重载 std::set::iterator
(又名双向迭代器)。但是,您可以使用 std::next
,来自 <iterator>
header 如下,实现相同的效果。
#include <iterator> // std::next
auto nthIter = std::next(it, ofst);
这基本上是在幕后增量 ofst
也有很多次。
std::set
有bidirectional iterators ,没有 random access iterators 这样的奢侈品,因此需要像这样递增。
话虽如此,您可以重载 operator+
(也许 operator-
)对于双向迭代器, which will not be recommended though .
关于c++ - 如何根据 set.begin() 的偏移量迭代 std::set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63500955/