How can I copy an entire vector into a queue?

前端 未结 3 964
滥情空心
滥情空心 2021-02-14 08:09

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?

3条回答
  •  我寻月下人不归
    2021-02-14 09:02

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

    std::vector v = get_vector();
    
    std::queue> q(std::deque(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 
    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).

提交回复
热议问题