2

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

4

2 回答 2

3

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

同样, anstd::back_insert_iterator与具有push_back成员的集合一起工作。写入back_insert_iterator转换为对集合的调用push_back

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

于 2013-05-25T17:55:08.857 回答
0

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

有了它,我在构建 insert_iterator 时不再有任何问题:

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

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

于 2013-05-26T21:19:06.433 回答