【发布时间】:2016-11-16 22:40:48
【问题描述】:
我正在编写一个允许输入类似俄罗斯方块的形状的程序。我将这些形状存储在布尔值的二维向量中,因此它们看起来像:
110 | 1 | 111
011 | 1 | 010
| 1 | 111
// Where a 0 denotes "empty space"
然后我指向这些二维向量中的每一个,并将这些指针存储在一个称为形状的向量中。 我的问题在于访问那些单独的 0 和 1(以便将它们与其他形状进行比较)。
例如,给定:
vector<vector<bool> > Shape;
vector<Shape *> shapes;
其中形状有三个元素指向我之前给出的二维向量,我希望能够访问第一个形状的 (0, 1) 位置中的 1。
我试过了:
shapes[index]->at(0).at(1);
shapes[index]->at(0)[1];
shapes[index][0][1];
在许多其他事情中,但这些似乎都没有给我我想要的东西。我对指针还很陌生,所以我希望我不只是遗漏了一些明显的东西。
提前谢谢你!
根据要求,这是我的一大段代码。
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
typedef vector<vector<bool> > Shape;
class ShapeShifter {
public:
ShapeShifter(int argc, char **argv);
void Apply(int index, int row, int col);
bool FindSolution(int index);
void AddShape(Shape *newShape);
void AddMove(int index, int row, int col);
void PrintMoves();
void PrintGrid();
protected:
vector<vector<bool> > grid;
vector<Shape *> shapes;
vector<string> moves;
};
void ShapeShifter::Apply(int index, int row, int col) {
int i, j, k;
int y = 0, z = 0;
if((row + shapes[index]->size() > grid.size()) || (col + shapes[index]->at(0).size() > grid[0].size())) {
return; // shape won't fit
}
for(i = row; i < (row + shapes[index]->size()); i++) {
for(j = col; j < (col + shapes[index]->at(0).size()); j++) {
if(shapes[index]->at(y)[z] == 1) {
if(grid[i][j] == 0) {
grid[i][j] = 1;
}
else {
grid[i][j] = 0;
}
}
z++;
}
z = 0;
y++;
}
return;
}
在此我有一个布尔网格,我试图用给定索引中的形状来掩盖它,如果形状为 1,则网格中相应元素中的布尔值将被翻转。
shape 向量在标准输入上填充线条,如下所示:
ShapeShifter sshift(argc, argv);
Shape *newShape;
vector<bool> shapeLine;
int i, j;
string line;
while(getline(cin, line)) {
j = 0;
newShape = new Shape;
for(i = 0; i < line.size(); i++) {
if(line[i] == ' ') {
j++;
}
else {
shapeLine.push_back(line[i] - '0');
}
}
newShape->push_back(shapeLine);
sshift.AddShape(newShape);
line.clear();
}
void ShapeShifter::AddShape(Shape *newShape) {
shapes.push_back(newShape);
}
【问题讨论】:
-
giving me what I want是什么意思?你在期待什么?你得到了什么? -
张贴零碎的代码没有帮助。请发帖minimal reproducible example。
-
当您评估最后发布的三个表达式时,您会得到什么值。
-
@Ben 我希望它返回 1,这样我就可以将它与另一个布尔值进行比较,看看它们是否相同/等等。类似 if(shapes[index]->at(0).at(1) == 1) {do this}
-
@Toy_Reid 更改网格值的
if / else语句可以简单地替换为if(shapes[index]->at(y)[z]) grid[i][j] = !grid[i][j];。另外,为什么你需要在你的程序中使用指针?我认为不需要它们。