访问指向多维向量的指针向量中的元素
Access elements in a vector of pointers to multi-dimensional vectors
我正在编写一个程序,允许输入类似俄罗斯方块的形状。我将这些形状存储在一个二维布尔向量中这样它们看起来就像:
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);
相关文章:
- 函数向量_指针有不同的原型,我可以构建一个吗
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 使用向量类的c++指针
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 如何更改唯一指针向量的可见性
- C++ 独特指针练习的向量
- C 中的向量指针的清晰图
- 当向量位于内部类中时,如何删除指向对象的向量指针
- std::向量指针
- 指向结构体的向量指针错误
- 删除指向指针的向量指针时出错
- 映射不同类型的向量指针
- 在c++中传递向量指针
- 虚拟类的向量:指针是干净的方法吗
- 如何从另一个向量/对象集构造新的向量/指针集
- 模型视图控制器- c++向量指针,太多的传递
- 为什么向量指针占用这么多内存?
- 删除条目向量指针的静态映射c++
- 复向量指针
- c++数组向量指针的初始化