问题
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