Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
Bill Cheatham Avatar asked Nov 17 '11 13:11

Bill Cheatham


1 Answers

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).

like image 173
Kerrek SB Avatar answered Oct 11 '22 05:10

Kerrek SB