how can i store array to queue in c++

你说的曾经没有我的故事 提交于 2019-12-11 03:12:41

问题


queue < int* > qq;

for (int i = 0; i < N; i++) {
    int cc[2] = {i, i + 1};
    qq.push(cc);
}

The N is large but not Exact so I want use queue. I want to store many arrays to queue,but the arrays which qq stored are the same one. How can I do it?


回答1:


Your code won't work. Each cc has the same stack location in the loop.

You need to allocate the cc array in the heap, perhaps using int *cc = new int[2]; (but then you need to delete it later).

A better way would be to have cc declared as a std::vector or std::array or std::tuple (in C++11).




回答2:


What you're doing is syntactically right, but conceptually wrong. You're inserting local array which gets created in each iteration and destroyed at the end of the iteration; that leaves qq in an unusable state. Outside the loop, dereferencing any element of qq would invoke undefined behavior.

Use std::vector:

std::queue<std::vector<int>> qq;

for (int i = 0; i < N; i++) {
    std::vector<int> cc{i, i + 1};
    qq.push(cc);
}



回答3:


You push each time the same address, namely, cc. You need to dedine a struct holding the two values, like so:

struct CC {
    int x, y;
    CC(int _x, int _y) : x(_x), y(_y) {}
}

queue<CC> qq;

and then..

qq.push(CC(i, i + 1));


来源:https://stackoverflow.com/questions/13680140/how-can-i-store-array-to-queue-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!