如下列代码,
#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个队列互相独立。
Your
queue
is declared inside thefor
loop. Each loopqueue
is created at the same location and then destroyed by . So you always get the same address. When exiting the loop, allqueue
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.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