c++ - 使用不同功能的队列中的打印元素不会在_start程序中全局清空队列。还有更多解释吗?

标签 c++ c++11 reference stl c++14

也许这是一个很简单的问题,但我无法概括为什么结果是它的样子。
考虑下面的简单代码。

#include <iostream>
#include <queue>

void print_queue(std::queue<int> q)
{
    while( !q.empty() )
    {
       std::cout << q.front();
       q.pop();
    }
    std::cout << std::endl;
    std::cout << "The size of the queue in the print function: " << q.size() << std::endl;
}


int main() {

   std::queue<int> my_queue;
   for ( const int &item : {1, 2, 3, 4, 5, 6, 7} )
   {
       q.push(item);
   }
   print(my_queue);
   std::cout << "The size of the queue in the main loop: " << my_queue.size() << std::endl;

   return 0;
}


预期的输出将是:
1 2 3 4 5 6 7
The size of the queue in the print function: 0
The size of the queue in the main loop: 7

我的问题是,为什么我要打印的队列没有副作用。
在打印出尺寸时,是否两次都没有队列?

最佳答案

函数print_queue和函数main处理两个不同的队列。您应该通过引用将队列传递给main。

也就是说,函数print_queue的参数应为引用类型。例如

void print_queue(std::queue<int> &q)
                                 ^^

否则,该函数将处理原始队列的副本。结果,原始队列未更改。

关于c++ - 使用不同功能的队列中的打印元素不会在_start程序中全局清空队列。还有更多解释吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58656732/

相关文章:

c++ - 当使用 'auto' 时,从函数返回引用是否会导致创建新的临时对象?

c++ - 如何在 C++ 中修复动态数组中的 "Out of Memory"

C++ 运算符使用友元函数重载。尝试添加多个对象失败

c++ - constexpr如何推导值?

c++ - 具有 std::array 和 c 样式数组成员的可变参数模板结构之间的区别

c++ - 强制从函数中推导模板以在适用的情况下生成 const 引用

python 按值而不是按引用列出

c++ - 在成员初始化器列表中使用大括号初始化会导致 std::vector 复制构造中的堆栈溢出(使用 GCC 但不使用 Clang)

c++ - 使用 C++ 和 ffmpeg 从 mp2 流中提取 KLV 数据

.net - .NET 中的弱引用实现