c++ - 自定义迭代器和 insert_iterator

标签 c++

我最近编写了我的第一个自定义迭代器(耶!)它在容器(缓冲区)之上运行,当前是 std::vector 缓冲区,但至少在理论上应该与任何其他标准容器一起工作,具有可变长度字节编码数据。没有什么花哨。基本上,我的迭代器所做的就是计算到达缓冲区中下一个条目的步长。我正在使用 std::bi Direction_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::inserterstd::back_inserter 只是创建 insert_iteratorback_insert_iterator 的函数模板分别,但使用类型推导,因此您不需要指定类型。

关于c++ - 自定义迭代器和 insert_iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16752038/

相关文章:

c++ - 调试时自动禁用 Visual Studio 断点

c++ - isalpha() 函数为字符串中的字符返回 false

c++ - 列出线程

c++ - 对谷歌风格指南的 Sublime Text 支持

c++ - 对类的静态成员的 undefined reference

c++ - STL:使用 ptr_fun 为 "const T &"类型调用 bind2nd

c++ - MFC中如何在资源链中查找资源?

c++ - Qt永久删除文件

c++ - move 哪个 throw ?

c++ - 我已经在C++中创建了一个函数来递归地反转字符串,但是如何使函数在以后打印endl?