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 队列
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
