Search code examples
c++stlcopyqueueinsert-iterator

Insert into an STL queue using 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() ) );

But this fails to compile, complaining that begin is not a member of std::queue.

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.

Am I missing something obvious, or do insert_iterators just not work with queues?


Solution

  • 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;
    };
    

    Used like this:

    std::queue<int> qi;
    
    QueueAdapter< std::queue<int> > qiqa( qi );
    
    std::copy( v.begin(), v.end(), std::back_inserter( qiqa ) );