Insert into an STL queue using std::copy(使用 std::copy 插入 STL 队列)
问题描述
我想使用 std::copy 将元素插入这样的队列:
I'd like to use std::copy to insert elements into a queue like this:
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
queue<int> q;
copy( v.begin(), v.end(), insert_iterator< queue<int> >( q, q.front() ) );
但是编译失败,抱怨 begin 不是 std::queue 的成员.
But this fails to compile, complaining that begin is not a member of std::queue.
注意:我也用 std::inserter 尝试过 - 这也失败了,这次说 'reference' 不是 'std::queue' 的成员.std::back_inserter 和 std::back_insert_iterator 也因相同的错误而失败.
Note: I tried it with std::inserter too - this also failed, this time saying that 'reference' is not a member of 'std::queue'. std::back_inserter and std::back_insert_iterator also fail with the same error.
我是否遗漏了一些明显的东西,或者 insert_iterator 只是不适用于队列?
Am I missing something obvious, or do insert_iterators just not work with queues?
推荐答案
不幸的是 std::queue 将名为 push_back 的函数改编"为仅 push 这意味着标准的 back_insert_iterator 不起作用.
Unfortunately std::queue 'adapts' the function known as push_back to just push which means that the standard back_insert_iterator doesn't work.
可能最简单的方法(尽管在概念上很难看)是用一个寿命短的容器适配器适配器[原文如此](呃!)来适应容器适配器,该适配器的寿命与后插入迭代器一样长.
Probably the simplest way (albeit conceptually ugly) is to adapt the container adapter with a short lived container adapter adapter[sic] (eugh!) that lives as long as the back insert iterator.
template<class T>
class QueueAdapter
{
public:
QueueAdapter(std::queue<T>& q) : _q(q) {}
void push_back(const T& t) { _q.push(t); }
private:
std::queue<T>& _q;
};
这样使用:
std::queue<int> qi;
QueueAdapter< std::queue<int> > qiqa( qi );
std::copy( v.begin(), v.end(), std::back_inserter( qiqa ) );
这篇关于使用 std::copy 插入 STL 队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 std::copy 插入 STL 队列
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
