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

标签 c++ algorithm c++11 iterator stdset

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

即具有 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::setbidirectional iterators ,没有 random access iterators 这样的奢侈品,因此需要像这样递增。


话虽如此,您可以重载 operator+ (也许 operator- )对于双向迭代器, which will not be recommended though .

关于c++ - 如何根据 set.begin() 的偏移量迭代 std::set?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63500955/

相关文章:

c++ - 错误 : no matching function for call to 'Rectangle::Rectangle()'

c++ - 是否可以在程序中使用 std::string 作为 if else 语句的一部分

c# - 如何在 C# 中解决 Randomize in place 算法?

c++ - 通过构造函数和析构函数实现 RAII 是否被认为是错误的 'Modern C++'?

c++ - 为什么输出首先显示文件 2?

c++ - 编译器错误预期嵌套名称说明符

c++ - 恩洛曼和复制 map

java - 将 Java 中的 C++ DLL 与 JNA 结合使用

algorithm - 使列表中每个位置的硬币数量相等所需的最少硬币移动次数

c++ - 找到适合整数的最大斐波那契数的最快方法是什么?