使用 std::copy 插入 STL 队列

2022-01-07 00:00:00 复制 queue c++ stl insert-iterator

我想使用 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_inserterstd::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 ) );

相关文章