简体   繁体   English

C++ 队列<string>带有双花括号的初始化列表</string>

[英]C++ queue<string> initializer list with double curly braces

From this question Why can't I construct a queue/stack with brace-enclosed initializer lists?从这个问题为什么我不能用大括号括起来的初始化列表构造一个队列/堆栈? (C++11) , we know that it won't work by constructing a queue with single curly braces. (C++11) ,我们知道用单个花括号构造一个队列是行不通的。 Because queue is container adapter which does not have constructor with initializer list.因为队列是容器适配器,它没有带有初始化列表的构造函数。

However, why below approach will work?但是,为什么下面的方法会起作用? Does double curly braces call queue's constructor with container argument?双花括号是否使用容器参数调用队列的构造函数? So the inner curly brace {"hello"} is considered as a vector<string> ?所以内花括号{"hello"}被认为是一个vector<string>

    queue<string> q{{"hello"}}; //Question: why init with double curly braces?

If you look at this std::queue constructor reference you will see that there is no overload taking an initializer list.如果您查看std::queue构造函数参考,您将看到没有采用初始化列表的重载。

There is however an overload taking the underlying container.然而,底层容器存在过载。

So what happens here is that the outer {} pair is for the construction of the std::queue objects, and the inner {} pair is to implicitly create the underlying container, which is then passed to the queue.所以这里发生的是外部{}对用于构造std::queue对象,而内部{}对用于隐式创建底层容器,然后将其传递给队列。

In short:简而言之:

std::queue<std::string> q{{ "hello" }};

is somewhat equivalent to:有点等价于:

std::deque<std::string> temporary_container{ "hello" };
std::queue<std::string> q{ temporary_container };

[Note that the default container for std::queue is std::deque ] [注意std::queue的默认容器是std::deque ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM