Bill Cheatham
Bill Cheatham

Reputation: 11917

How can I copy an entire vector into a queue?

I am looking to copy the entire contents of a vector into a queue in C++. Is this a built in function or is it nessesary to loop over each element?

Upvotes: 19

Views: 46274

Answers (3)

log0
log0

Reputation: 10917

Probably the best way is to directly push elements into the queue.

std::vector<T> v;
...
std::queue<T> q;
for (const auto& e: v)
  q.push(e);

Even using std::copy is tedious since you have to wrap the queue in an adapter (Insert into an STL queue using std::copy).

Upvotes: 13

Kerrek SB
Kerrek SB

Reputation: 476950

If you make a new queue, you can use the constructor:

std::vector<int> v = get_vector();

std::queue<long int, std::deque<long int>> q(std::deque<long int>(v.begin(),
                                                                  v.end()));

(You can change the underlying container to taste, though deque is probably the best.)

If the queue already exists, there's no range-based algorithm, though, you can easily write your own:

template <typename Iter, typename Q>
push_range(Q & q, Iter begin, Iter end)
{
    for ( ; begin != end; ++begin)
        q.push(*begin);
}

As an aside: If your algorithm requires that amount of flexibility, you're probably better of just using a std::deque in the first place. The container adapters (queue and stack) should only be used if you want to say explicitly, "this is the behaviour I want" (i.e. push/pop).

Upvotes: 23

Goodwine
Goodwine

Reputation: 1718

The queue's constructor is as follows:

explicit queue ( const Container& ctnr = Container() );

So you can have some vector v and construct a queue from it.

vector<int> v;
deque<int> d;
/* some random magic code goes here */
queue<int, deque<int>> q(d(v));

However you can't do this to push_back elements in an already initialized q. You could use another Container, empty your queue, append your vector to that container, and create a new queue from that vector; but I'd iterate rather than doing all that.

Final answer: No, there is no such method implemented for queues, you could use deque or iterate your vector.

Upvotes: 2

Related Questions