我最近写了我的第一个自定义迭代器(是!),它在容器(缓冲区)(目前是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呢?
最佳答案
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
的函数模板,但是使用类型推导,因此您无需指定类型。
关于c++ - 自定义迭代器和insert_iterator,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16752038/