如何将 std::queue 转换为 std::vector [英] How to convert std::queue to std::vector

查看:49
本文介绍了如何将 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.

这样做的优点是:

  1. 在双端队列两端的恒定时间插入和删除

  1. 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()});
}

queuevector 的非变异转换是不可能的.

A non-mutating conversion of a queue to a vector is not possible.

这篇关于如何将 std::queue 转换为 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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