如何根据 set.begin() 的偏移量迭代 std::set?

Yak*_*kov 2 c++ algorithm iterator stdset c++11

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

即有开始的迭代器:

auto it = set.begin()
Run Code Online (Sandbox Code Playgroud)

我需要到达具有偏移量的迭代器ofst

it + ofst
Run Code Online (Sandbox Code Playgroud)

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

JeJ*_*eJo 5

我需要去迭代器具有偏移ofstit + ofst:有没有办法做到这一点?

不,没有operator+为此定义重载std::set::iterator(又名双向迭代器)。但是,您可以按如下方式使用 std::next, from <iterator>header 来实现相同的效果。

#include <iterator>  // std::next

auto nthIter = std::next(it, ofst);
Run Code Online (Sandbox Code Playgroud)

这基本上在幕后ofst也会增加时间。

std::set具有双向迭代器,它有没有像奢侈品随机访问迭代器,因此需要这样的增量。


话虽如此,您可以为双向迭代器重载operator+( 并且可能operator-),但不推荐这样做