2016-11-16 110 views
0

我正在編寫一個允許輸入類似俄羅斯方塊形狀的程序。我存儲在布爾的2-d矢量這些形狀所以他們會再看看這樣的:訪問多維矢量指針向量中的元素

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

我再點到每臺2-d載體和這些指針存儲在一個名爲矢量形狀。 我的問題在於訪問那些個人的0和1(爲了將它們與其他形狀進行比較)。

例如,給定:

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

其中形狀具有指向2-d向量I先前給出了三個元件,我希望能夠訪問1中的(0,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中的網格的對應元素的布爾將被翻轉。

形狀矢量填充與標準輸入線,像這樣:

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

是什麼'給我什麼,我want'的意思嗎?你在期待什麼?你得到了什麼? –

+2

發佈代碼段沒有幫助。請發佈[mcve]。 –

+0

當您評估最後發佈的三個表達式時,您會得到什麼值。 –

回答

0

你爲什麼要使用string載體而不僅僅是焦炭的二維數組或任何你需要什麼?那麼你可以輕鬆訪問它們:shape[x][y]

不管怎麼說,你現在有它設置,您可以訪問你想要這樣的價值的方式: shapes[0]->at(0).at(1);

+0

由於'shapes [0]'評估爲指針,所以這不起作用。你必須解除引用它才能訪問'vector '。 –

+0

Woops,沒有看到他使用了'Shape *',必須改成' - >' –

+0

我不小心收入了錯誤的typedef,它實際上應該是矢量>,而不是矢量。 –