【问题标题】:How to iterate std::set based on offset from set.begin()?如何根据 set.begin() 的偏移量迭代 std::set?
【发布时间】:2020-12-09 13:07:58
【问题描述】:

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

即有开始的迭代器:

auto it = set.begin()

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

it + ofst

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

【问题讨论】:

  • std::next 但对于非连续容器,例如std::set,它基本上必须增加 n 次。

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


【解决方案1】:

我需要找到具有偏移量的迭代器 ofst: it + ofst: 有吗 有办法吗?

不,没有为此为std::set::iterator(又名双向迭代器)定义的operator+ 重载。但是,您可以使用来自<iterator> 标头的std::next,如下所示。

#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-)。

【讨论】:

    猜你喜欢
    • 2012-10-03
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多