【问题标题】:custom iterator and insert_iterator自定义迭代器和 insert_iterator
【发布时间】:2013-05-25 17:17:45
【问题描述】:

我最近编写了我的第一个自定义迭代器(耶!)它在一个容器(缓冲区)之上运行,目前是一个 std::vector 缓冲区,但至少在理论上应该与任何其他标准容器一起工作,可变长度字节编码数据。没有什么花哨。基本上,我的迭代器所做的是计算要走多远才能到达缓冲区中的下一个条目。我将 std::bidirectional_iterator_tag 用于我的迭代器。

无论如何,我已经对其进行了一些测试,并且在使用它进行迭代和一些标准操作(如 std:distance 或 std::copy)时它工作得很好。

然后我想到能够将新项目插入缓冲区会非常整洁。我们如何做到这一点?好吧,我认为我现在有一个迭代器,我可以使用一些 std::insert 函数。没找到,std::insert_iterator/std::inserter 好像是要走的路。

那没用。

std::vector<unsigned char> dataBuffer;
std::vector<unsigned char> otherDataBuffer;

//*Fill dataBuffer with data*

ByteCrawlerIterator<std::vector<unsigned char> > insertionPoint(dataBuffer.begin());

//*pick an insertion point (this works)*
std::advance(insertionPoint, 5);

//*this will produce a lot of really ugly and confusing compiler errors*
std::insert_iterator<std::vector<unsigned char> > insert_itr(dataBuffer, insertionPoint);

//*Well we don't get this far, but I intended to use it something like this*
std::copy(ByteCrawlerIterator(otherDataBuffer.begin()), ByteCrawlerIterator(otherDataBuffer.end()), insert_it);

我假设插入迭代器是一个能够与任何迭代器一起工作的适配器,甚至是自定义的。但我想那是不正确的,我该怎么做才能让我的自定义迭代器与 std::inserter 一起工作?还是我应该实现一个自定义的 insert_iterator?当我们讨论这个话题时,reverse_iterator 呢?

【问题讨论】:

    标签: c++


    【解决方案1】:

    std::insert_iterator 是一种适配器,但它适用于集合,而不是迭代器。为了完成它的工作,它要求集合有一个insert 成员。当您写信给insert_iterator 时,它会被转换为对集合的insert 成员的调用。

    同样,std::back_insert_iterator 与具有 push_back 成员的集合一起使用。写信给back_insert_iterator 会转化为调用集合的push_back。

    std::inserter 和std::back_inserter 只是分别创建insert_iterator 或back_insert_iterator 的函数模板,但使用类型推导,因此您无需指定类型。

    【讨论】:

    • 嗯,我几乎想通了,但它可以像我尝试做的那样与自定义迭代器一起使用,还是你必须使用容器提供的迭代器,在我的示例中,我试图构建一个insert_iterator 来自我的 ByteCrawler 迭代器。我做得不对还是不应该这样工作?
    • @AcidFloppy:至少在我看来,你显然想要的是这样的:std::copy(ByteCrawlerIterator(otherDataBuffer.begin()), ByteCrawlerIterator(otherDataBuffer.end()), std::back_inserter(dataBuffer)); 然而,你的ByteCrawlerIterator 与普通的std::vector&lt;unsigned char&gt;::iterator 有什么不同呢? .
    • 它并没有那么不同,实际上包装了一个vector::iterator,但它计算了到达缓冲区中下一个字节编码项的字节数,它不一定是std::向量。每个编码项的长度都是可变的。我开始相信这是不可能的,对于调用 vector.insert 的插入器,它需要我包装的实际缓冲区迭代器,我想我总是可以为底层迭代器提供访问器......但它有点难看那么我的意图:(
    【解决方案2】:

    如果有人对底层容器迭代器的转换运算符感兴趣,似乎可以解决问题。

    这样我在构建插入迭代器时不再有任何问题:

    std::insert_iterator<std::vector<unsigned char> > insert_itr(dataBuffer, insertionPoint);
    

    更重要的是,它实际上似乎在起作用!

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 2015-02-04
      • 2013-02-17
      • 2020-04-21
      • 1970-01-01
      • 2015-11-19
      • 2013-09-02
      • 2016-06-18
      相关资源
      最近更新 更多