使用std :: copy插入STL队列 [英] Insert into an STL queue using std::copy

查看:155
本文介绍了使用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 'adapts'函数称为 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.

也许最简单的方法(尽管在概念上是丑陋的)是使用一个短生命周期的容器适配器适配器[eic!]来适应容器适配器,只要后插入迭代器。

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队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆