c++队列存放的是元素的拷贝而不是元素本身,所以存在一个问题:当我们需要使用队列进行搜索,搜索的过程中又需要更改元素本身(如修改结构体内部某个指针等)应该怎么操作?
尝试使用指针队列:发现对于基本类型int
等可以实现(代码1),但自定义结构体、类无法实现。队列中存放的元素值都会变成最后一个入队的元素值。请问这是为啥??(灬ꈍ ꈍ灬)
代码1:int的指针队列
#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;
}
输出结果:390
是预期输出。
但将int更换成类以后:
#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;
}
输出结果:(结果太长,将其分为两列截成下图)
可以看到队列内部所有的值都变成了最后入队的那一个值
求助:这是为啥?