如何将std :: queue <char>复制到std :: string中?

Pat*_*ryk 1 c++ queue reference std char

我正在努力解决这段代码:

std::queue<char> output_queue;
std::string output_string
// put stuff into output_queue
while (!output_queue.empty())
    {
    output_string.insert(0,(output_queue.front()));
    output_queue.pop();
    }
Run Code Online (Sandbox Code Playgroud)

我不知道怎么办不行,因为它std::queue<char>::front()会返回一个char&,我不能把它放进去std::string.

chr*_*ris 5

你错过了一个insert插入一个字符的参数.您需要指定该角色的数量:

output_string.insert(0, 1, output_queue.front());
Run Code Online (Sandbox Code Playgroud)

如果你想让自己更容易,你也可以使用它std::deque代替std::queue并替换它:

std::deque<char> output_queue;
//fill output_queue in same way, but use push/pop_front/back instead of push/pop

std::string output_string(output_queue.begin(), output_queue.end());
output_queue.clear();
Run Code Online (Sandbox Code Playgroud)

它几乎与现在一样,因为你queue实际上是std::deque在默认情况下使用一个引擎盖.的deque,然而,支持迭代器,这使这成为可能,而不丑陋的代码依赖于底层的存储.

  • 不,他们没有.[`std :: queue`](http://en.cppreference.com/w/cpp/container/queue)不符合任何容器要求.不要将它与[`std :: deque`](http://en.cppreference.com/w/cpp/container/deque)混淆(它可能在内部由`std :: queue`使用,但是无论如何都是无法进入的.只要他不使用实际容器(如直接使用`std :: deque`),答案的第一部分仍然是他案例中的最佳解决方案. (2认同)