我需要使用一个双重队列,因为它作为一个有序容器具有良好的属性。我想把这个队列传递给接受向量的类构造函数。如果我直接这样做,就会得到以下错误:
候选构造函数不可行:对于第二个参数,没有已知的从'std::queue‘到'std::vector &’的转换
如何将队列转换为向量?
发布于 2016-08-01 13:02:30
这只是一种避免将从std::queue
复制到std::vector
的方法。不管你用不用,我都由你决定。
房地
std::queue
是一个容器适配器。默认情况下,内部container
是std::deque
,但是也可以将其设置为std::vector
。幸运的是,保存此容器的成员变量被标记为protected
。因此,您可以通过子类queue
来破解它。
解决方案(!)
template<typename T>
struct my_queue : std::queue<T, std::vector<T>>
{
using std::queue<T, std::vector<T>>::queue;
// in G++, the variable name is `c`, but it may or may not differ
std::vector<T>& to_vector () { return this->c; }
};
就这样!!
用法
my_queue<int> q;
q.push(1);
q.push(2);
std::vector<int>& v = q.to_vector();
演示。
https://stackoverflow.com/questions/38699268
复制相似问题