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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With