How can I copy an entire vector into a queue?

前端 未结 3 951
滥情空心
滥情空心 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 08:51

    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.

    0 讨论(0)
  • 2021-02-14 09:02

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

    0 讨论(0)
  • 2021-02-14 09:07

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

    0 讨论(0)
提交回复
热议问题