如何将整个向量复制到队列中? [英] How can I copy an entire vector into a queue?

查看:91
本文介绍了如何将整个向量复制到队列中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找将向量的全部内容复制到C ++中的队列中。这是一个内置函数还是需要遍历每个元素?

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?

推荐答案

如果创建新队列,则可以使用构造函数:

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);
}

顺便说一句:如果您的算法需要那么多的灵活性,最好只使用 std :: deque 。容器适配器( queue stack )仅在您要明确地说:这是行为我想要(即推送/弹出)。

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

这篇关于如何将整个向量复制到队列中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆