如何将 std::queue 转换为 std::vector

编程入门 行业动态 更新时间:2024-10-10 23:18:07
本文介绍了如何将 std::queue 转换为 std::vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要使用双打队列,因为它作为有序容器具有良好的属性.我想将此队列传递给接受向量的类构造函数.如果我直接这样做,我会收到以下错误:

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

    本文发布于:2023-11-05 18:17:49,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1561525.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:转换为   如何将   queue   std   vector

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!