我编写了一个C ++程序,该程序在队列中传递int数组的元素并执行一些简单的操作,我的代码:
#include <iostream>
#include <queue>
using namespace std;
int main()
{ queue<int> myqueue;
int screen[8][8] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1},
};
myqueue.push(screen[1][3]);
while(!myqueue.empty()){
//...stuff
}
}
在while循环中,我必须使用screen[1][3]
元素以及该元素的坐标(x,y)(在本例中为(1,3)。
但是,使用myqueue.push(screen[1][3])
仅将包含在该位置的项目放入队列(在本例中为1)。
如何修改放入队列中的元素,使其包含坐标(x,y)以及screen[x][y]
值?
答案 0 :(得分:1)
似乎您将元素的值放入队列中。但是,您还需要一些额外的数据,例如关联值的x,y位置。这里的问题不仅限于排队,而是范围广泛的情况。您应该使用参数(数据)对象模式。
创建一个结构以保存坐标(可能还有值),并在队列中使用该结构。
您可能会选择将x / y值编码为一个数字,但这可能是过早的优化
答案 1 :(得分:1)
您可以使用struct。 可能还有其他方法,例如使用map和list,但是struct正是为满足您的需求而设计的。
#include <iostream>
#include <queue>
using namespace std;
int main()
{
struct obj_pos {
int iValue;
int iX_pos;
int iY_pos;
};
queue<obj_pos> myqueue;
int screen[8][8] = {{1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0, 1, 1},
{1, 2, 2, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 0, 1, 0},
{1, 1, 1, 2, 2, 2, 2, 0},
{1, 1, 1, 1, 1, 2, 1, 1},
{1, 1, 1, 1, 1, 2, 2, 1},
};
obj_pos temp;
temp.iX_pos=1;
temp.iY_pos=3;
temp.iValue= screen[1][3];
myqueue.push(temp);
while(!myqueue.empty()) {
obj_pos localtemp = myqueue.front();
cout<<"X: "<<localtemp.iX_pos<<" Y: "<<localtemp.iY_pos<<" Value: "<<localtemp.iValue<<"\n";
myqueue.pop();
//...stuff
}
}
快乐编码。