如下列代码,
#include <iostream>
#include <queue>
int main() {
queue<int>* queue_list[10];
for (int l = 0; l < 10; ++l) {
queue<int> queue;
queue_list[l] = &queue;
}
for (int i = 0; i < 10; ++i) {
cout << queue_list[i] << endl;
}
}
我循环初始化了10个队列,可是我打印出来发现是同一个地址,会互相影响;请问如何可以让10个队列互相独立。
伊谢尔伦2017-04-17 14:48:23
Your queue
is declared inside the for
loop. Each loop queue
is created at the same location and then destroyed by . So you always get the same address. When exiting the loop, all queue
will no longer exist. queue_list[]
The pointers insideare all illegal.
If you want to create these queue
on the stack, queue<int> queue_list[10]
you can.
迷茫2017-04-17 14:48:23
What you write like this is to declare repeatedly in the loop, and the queue is all the same object on the stack. To put new on the heap
#include <iostream>
#include <queue>
int main() {
std::queue<int>* queue_list[10];
for (int l = 0; l < 10; ++l) {
std::queue<int> *queue = new std::queue<int>;
queue_list[l] = queue;
}
for (int i = 0; i < 10; ++i) {
std::cout << queue_list[i] << std::endl;
}
}