【问题标题】:How to properly use boost::iterator_adaptor for making cycling iterator?如何正确使用 boost::iterator_adaptor 制作循环迭代器?
【发布时间】:2012-02-10 14:24:04
【问题描述】:

我正在尝试实现循环迭代器,这在我的问题中非常有用。根据this 线程,我为此目的使用boost::iterator_adaptor,并且迭代器本身工作正常。实现很像this answer

但是,在同一句中同时操作cycle_iterator 和“native”IteratorBase 时会出现一些问题,如下所示:

vector<int> v;
vector<int>::iterator it = v.begin();
cyclic_iterator<vector<int>::iterator> cit(v.begin(), v.end());

if (cit != it)  // Don't compile
{
  ...
}

编译器生成错误 C2678: binary '!=' : no operator found 接受'cyclic_iterator' 类型的左操作数(或没有可接受的转换)。

我可以在cyclic_iterator 中为IteratorBase 明确指定operator!= 来解决它。但是,我需要显式重载operator==operator= 等等。

有没有更方便的方法可以让这些东西发挥作用?

【问题讨论】:

    标签: c++ boost stl iterator


    【解决方案1】:

    您是否尝试过这样做:

    template<class IteratorBase>
    class cycle_iterator : public  // (...) 
    {
        // (...)
        operator IteratorBase() {
            return base_reference();
        }
    };
    

    【讨论】:

    • 它只能处理it V cit的情况,其中V是一些比较运算符,但不能处理赋值甚至cit V it的情况。
    • 好吧,毕竟,我决定将这个转换运算符与赋值运算符一起添加,而不是将cyclic_itertor 与原始迭代器进行比较,因为它可能容易出错。所以我会接受你的回答:)
    猜你喜欢
    • 2021-08-09
    • 2012-01-22
    • 2012-08-29
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多