c++ - STL如何使构造10个不同的队列
高洛峰
高洛峰 2017-04-17 14:46:23
0
2
587

如下列代码,

#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个队列互相独立。

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
伊谢尔伦

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.

迷茫

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;
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template