2017-05-07 17 views
-2

我試圖從矩陣中索引一個元素,該矩陣已通過在結構中創建矢量向量進行了聲明。 這裏是我的代碼:結構的索引矩陣元素成員

#include <vector> 
using namespace std; 

const int MAX_DIM = 1000; 

struct TestStruct{ 
    int MAX_DIM; 
    vector<vector<int> > matrix (int MAX_DIM, vector<int>(int MAX_DIM)); 
}; 

int main(){ 
    TestStruct ts; 
    ts.MAX_DIM = 100; 
    ts.matriz[0][0] = 1; 

    return 0; 
} 

在編譯時我收到以下錯誤:

test.cpp:14:17: error: invalid types ‘<unresolved overloaded function type>[int]’ for array subscript 
    mierda.matriz[0][0] = 1; 

順便說一句,你知道任何其他「乾淨」的方式來聲明矩陣(不使用任何比其他從類矢量矢量)?

提前致謝!

+1

s/matriz/matrix/ – juanchopanza

+2

那不聲明矩陣,它聲明瞭一個函數。 –

+0

我該如何申報表格矩陣呢? – pitazzo

回答

1

在你的代碼,你的邏輯問題是,你覺得行:

vector<vector<int> > matrix (int MAX_DIM, vector<int>(int MAX_DIM)); 

創建您struct內的矩陣。

實際上,您剛剛宣佈了一個名爲matrix的函數,該函數返回vector<vector<int>。爲了使您的struct內成員對象,你需要刪除括號,因爲這樣的:

vector<vector<int> > matrix; 

我假設你想先指定MAX_DIM值,然後創建基於該值的矩陣。我會建議創建一個構造函數,該構造函數以int作爲參數,將該值分配給MAX_DIM,然後根據該值創建matrix,或者創建在訪問matrix之前需要調用的initialise()函數。

首先,最好的解決辦法:

using namespace std; 
const int MAX_DIM = 1000; 

struct TestStruct{ 
    TestStruct(int MD){ 
     MAX_DIM = MD; 
     matrix = vector<vector<int>>(MD, vector<int>(MD)); 
    } 

    int MAX_DIM; 
    vector<vector<int>> matrix; 

}; 

int main(){ 

    TestStruct ts(100); // matrix 100 by 100 
    ts.matrix[0][0] = 1; // works 

    return 0; 
} 

或者,如果你不想處理的構造函數:

using namespace std; 
const int MAX_DIM = 1000; 

struct TestStruct{ 

    int MAX_DIM; 
    vector<vector<int>> matrix; 

    void initialise(){ 
     matrix = vector<vector<int>>(MAX_DIM, vector<int>(MAX_DIM)); 
    } 

}; 

int main(){ 

    TestStruct ts; 
    ts.MAX_DIM = 100; // specify the size 
    ts.initialise(); // construct the matrix 
    ts.matrix[0][0] = 1; // works again 

    return 0; 
} 

注意第一個解決方案需要更少的代碼並在main函數內可讀性更高。如果您選擇第二個,則很容易忘記將值分配給MAX_DIM或致電initialise()