也许这是一个很简单的问题,但我无法概括为什么结果是它的样子。
考虑下面的简单代码。
#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/