访问指向多维向量的指针向量中的元素

Access elements in a vector of pointers to multi-dimensional vectors

本文关键字:向量 指针 元素 访问      更新时间:2023-10-16

我正在编写一个程序,允许输入类似俄罗斯方块的形状。我将这些形状存储在一个二维布尔向量中这样它们看起来就像:

110   |   1   |   111
011   |   1   |   010
      |   1   |   111
// Where a 0 denotes "empty space"

然后指向这些二维向量,并将这些指针存储在一个称为形状的向量中。我的问题在于如何访问这些单独的0和1(以便将它们与其他形状进行比较)。

例如:

vector<vector<bool> > Shape;
vector<Shape *> shapes;

其中shape有三个元素指向我之前给出的二维向量,我希望能够访问第一个shape(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;
}

在这里,我有一个bool的网格,我试图用给定索引中的形状来掩盖它,如果形状有一个1,网格中相应元素的bool将被翻转。

在标准输入上填充形状向量,如下所示:

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);
}

为什么要使用string的矢量,而不仅仅是一个2D的char数组或任何你需要的?然后你可以很容易地访问它们:shape[x][y]

无论如何,你现在设置的方式可以像这样访问你想要的值:shapes[0]->at(0).at(1);