我需要使用双打队列,因为它作为有序容器具有良好的属性.我想将此队列传递给接受向量的类构造函数.如果我直接这样做,我会收到以下错误:
I need to make use of a queue of doubles because of the good properties it has as an ordered container. I want to pass this queue to a class constructor that accepts vectors. If I do that directly I get the following error:
候选构造函数不可行:没有已知的转换来自'std::queue' 到 'std::vector &'对于第二个参数
candidate constructor not viable: no known conversion from 'std::queue' to 'std::vector &' for 2nd argument
如何将队列转换为向量?
How to cast a queue to a vector?
推荐答案模拟 queue_like 行为和 vector-like 行为的正确容器是 std::deque.
The correct container to model both queue_like behaviour and vector-like behaviour is a std::deque.
这样做的优点是:
在双端队列两端的恒定时间插入和删除
constant-time insertion and deletion at either end of the deque
能够在不破坏双端队列的情况下迭代元素
ability to iterate elements without destroying the deque
std::deque 支持 begin() 和 end() 方法,这意味着您可以构造一个向量(具有兼容的值-直接输入).
std::deque supports the begin() and end() methods which means you can construct a vector (with compatible value-type) directly.
#include <vector> #include <deque> class AcceptsVectors { public: AcceptsVectors(std::vector<double> arg); }; int main() { std::deque<double> myqueue; auto av = AcceptsVectors({myqueue.begin(), myqueue.end()}); }queue 到 vector 的非变异转换是不可能的.
A non-mutating conversion of a queue to a vector is not possible.
更多推荐
如何将 std::queue 转换为 std::vector
发布评论