C++ 如何将整个向量复制到队列中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8168127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I copy an entire vector into a queue?
提问by Bill Cheatham
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?
我希望将向量的全部内容复制到 C++ 中的队列中。这是一个内置函数还是遍历每个元素是必要的?
回答by Kerrek SB
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.)
(您可以根据口味更改底层容器,但deque
可能是最好的。)
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).
顺便说一句:如果您的算法需要如此大的灵活性,那么您最好std::deque
首先使用 a 。容器适配器(queue
和stack
)应该只在您想明确地说“这是我想要的行为”(即推送/弹出)时使用。
回答by log0
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).
即使使用 std::copy 也很乏味,因为您必须将队列包装在适配器中(使用 std::copy 插入 STL 队列)。
回答by Goodwine
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.
所以你可以有一些向量 v 并从中构造一个队列。
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.
但是,您不能对已经初始化的 q 中的 push_back 元素执行此操作。您可以使用另一个容器,清空队列,将向量附加到该容器,然后从该向量创建一个新队列;但我会迭代而不是做所有这些。
Final answer: No, there is no such method implemented for queues, you could use deque or iterate your vector.
最终答案:不,没有为队列实现这样的方法,您可以使用 deque 或迭代您的向量。