c++ - 将 vector 复制到队列中

标签 c++ stl

我有 vector

 std::vector<OrderInfo *> vec

和一个队列
queue<OrderInfo *> *myQueue = new queue<OrderInfo *>;

我想将 vector 复制到队列中。我尝试使用How can I copy an entire vector into a queue?这个答案以及这个Insert into an STL queue using std::copy

但它不起作用,如何使它起作用?

这是我尝试的:
myQueue =新队列(vec.begin(),vec.end());
我有

error: no matching function for call to ‘std::queue::queue(std::vector::iterator, std::vector::iterator)’ myQueue = new queue(vec.begin(), vec.end());



当我尝试这个:
std::copy(vec.begin(),vec.end(),std::back_inserter(myQueue));

我有:

required from ‘BacStrategy::BacStrategy(EZXConnectionHandler&, const string&, bool, const double&, int) [with Event_Type = EZXOrderEventHandler; std::__cxx11::string = std::__cxx11::basic_string]’ /home/yaodav/Desktop/git_repo/test/main.cpp:324:51: required from here /usr/local/include/c++/7.4.0/bits/stl_iterator.h:490:7: error: ‘std::queue*’ is not a class, struct, or union type operator=(const typename _Container::value_type& __value)

最佳答案

myQueue是一个指针,而不是队列,并且不能传递给std::back_inserter。要解决此问题,请不要将其声明为指针。

此外,如您发布的第二个链接所述,std::back_inserter不能与std::queue一起使用。

相反,只需写

std::queue<OrderInfo*> myQueue{
    std::deque<OrderInfo*>(vec.begin(), vec.end())
};

如果您确实需要指针,请按如下所示修改代码:
std::queue<OrderInfo*>* myQueue = new std::queue<OrderInfo*>{
    std::deque<OrderInfo*>(vec.begin(), vec.end())
};


最后,如果您需要填充已经初始化的队列,请按照以下步骤操作:使用以上命令创建一个临时队列并将其分配给指针:
*myQueue = std::queue<OrderInfo*>{std::deque<OrderInfo*>(vec.begin(), vec.end())};

如果看起来太乱了,您还可以为该队列创建一个临时变量,但是在这种情况下,您需要使用std::move来确保队列是移动分配的,而不是昂贵地复制:
auto tmp = std::queue<OrderInfo*>{std::deque<OrderInfo*>(vec.begin(), vec.end())};
*myQueue = std::move(tmp);

同样,请仔细考虑是否要存储OrderInfo而不是OrderInfo的指针。

关于c++ - 将 vector 复制到队列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59878953/

相关文章:

c++ - 我应该将这些方法声明为 const 吗?

c++ - 封闭突变体 handle

c++ - 传输流 - 提取信息

带有 unique_ptr 的 C++ 嵌套映射

c++ - 指针在类成员函数中没有被修改

c++ - fscanf C++ 等价物

c++ - 在模块(exes和dlls)之间使用STL(TR1)shared_ptr是否安全

c++ - 在运行时指定的多个谓词

c++ - VS2010 SP1 中 C++ 和 STL 的新增功能是什么?

c++ - C++17 中的 Python 样式装饰器