0

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. 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>?

    queue<string> q{{"hello"}}; //Question: why init with double curly braces?
thinkdeep
  • 945
  • 1
  • 14
  • 32
  • The normal approach to this kind of situation is keep adding braces until it works – M.M Apr 14 '21 at 05:40

1 Answers1

4

If you look at this std::queue constructor reference you will see that there is no overload taking an initializer list.

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.

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]

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks. How do you figure out that the underlying container for `queue` is `deque` instead of `vector`? I don't see this info in the link. – thinkdeep Apr 14 '21 at 19:01
  • @thinkdeep Go a step up to the [`std::queue`](https://en.cppreference.com/w/cpp/container/queue) reference, where you can see the template arguments. More specifically `class Container = std::deque`. – Some programmer dude Apr 14 '21 at 19:07