我最近写了我的第一个自定义迭代器(耶!)它在一个容器(缓冲区)之上运行,目前是一个 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 呢?