The c++ queue stores the copy of the element instead of the element itself, so there is a problem: when we need to use the queue to search, how to change the element itself (such as modifying a pointer in the structure) during the search process?
Try to use pointer queues: found that it int
can be implemented for basic types, etc. (code 1), but custom structures and classes cannot be implemented. The value of the element stored in the queue will become the value of the last element in the queue. Excuse me, why is this? ? (灬ꈍ ꈍ灬)
Code 1: Int's pointer queue
#include<iostream>
#include<queue>
using namespace std;
queue<int*> q;
int main(){
int i = 0;
q.push(&i);
i = 3;
int j = 100;
q.push(&j);
cout<<*q.front();
q.pop();
j = 90;
cout<<*q.front();
return 0;
}
Output result: 390
the expected output.
But after replacing int with a class:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 4;
class Game { //棋局类
public:
int s[N][N]; //当前棋局状况
Game * father; //父节点指针
void show() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cout << s[i][j];
}
cout << endl;
}
cout << endl;
}
};
int main() {
queue<Game *> q;
for (int j = 0; j < 4; j++) {
Game i;
i.s[0][j] = j;
//Game * p = (Game*)malloc(sizeof(Game));
//p = &i;
q.push(&i);
(*q.front()).show();
}
Game i;
for (int j = 0; j < 4; j++) {
i = *q.front();
q.pop();
i.show();
cout << "队列长度:" << q.size() << endl;
}
system("pause");
return 0;
}
Output result: (the result is too long, divide it into two columns and cut it into the following figure)
You can see that all the values in the queue have become the last value in the queue
Help: Why is this?