How can I copy an entire vector into a queue?

天涯浪子 提交于 2020-07-05 06:59:08

问题


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?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/8168127/how-can-i-copy-an-entire-vector-into-a-queue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!