How to copy the entire vector into a queue?

I want to copy the entire contents of a vector into a queue in C ++. Is this a built-in function or is it necessary to link each element?

+4
source share
3 answers

If you create 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 base container to taste, although deque is probably the best.)

If the queue already exists, then there is no range-based algorithm, however 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); } 

Aside: if your algorithm requires such flexibility, you are probably best off using std::deque first. Container adapters ( queue and stack ) should only be used if you want to explicitly indicate "this is the behavior I want" (i.e. Push / pop).

+11
source

Probably the best way is to directly insert items 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 the adapter ( Insert into the STL queue using std :: copy ).

+3
source

The queue constructor is as follows:

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

So, you can have some vector v and build 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 cannot do this for push_back elements in an already initialized q. You can use another Container, empty your turn, add your vector to this container and create a new queue from this vector; but I will sort it out, and not do it all.

Final answer: No, this method is not implemented for queues, you can use deque or iterate your vector.

+2
source

Source: https://habr.com/ru/post/1381704/


All Articles