2013-05-08 31 views
0

我是一名C++初學者,我曾經在2D矢量上做過矢量處理。我經常上網,但互聯網上的數據與2D矢量非常具體。 我需要建立一個給定輸入文件的圖形,然後將Kruskal算法應用於最小生成樹。使用2D向量實現相鄰矩陣C++

我的方法:

A1, A2, A3.....An would be the first row and col of my 2d Vectors and they will 
contain name. I will read the input file and start matching the names. 
And then at graph[i][j] I will put the weight. 

    A1 A2 A3...... 

A1 w w w ....... 
A2 w w w ....... 
A3 w w w ....... 

。 。 。 。 現在,我想是這樣的:

struct mat{ 
     string name; 
} 

int main(){ 
vector<vector<mat>> matrix; 
// In order to insert 
vector<mat> tempVec; 
tempVec[0].name = "stack"; 
matrix.push_back(tempVec); 
} 

現在我不知道,當我做tempVec[0].name,0表示該行或矩陣的山坳。如果它表示行,那麼我怎麼知道哪個列被訪問。 我的意思是vector.push_back(tempVec),將我的矩陣中的哪個位置分配給數據。我知道我可以訪問Matrix [i] [j]等單個元素。但是,如何將權重分配給特定的行,列的位置,然後訪問它。

此外,你認爲Kruskal's Method會是一個很好的實現。

請簡單的在您的代碼和說明。 並提前致謝。

+0

確定它不是matrix.push_back(tempVec); ? – 2013-05-08 12:32:24

+0

請參閱http://stackoverflow.com/questions/5493474/graph-implementation-c – Bull 2013-05-08 12:33:31

+0

@ user2151446我想使用2D矢量來做到這一點。我認爲這會容易得多。 – 2013-05-08 12:35:46

回答

0

使用vector<vector<T>>是表示矩陣的相當不理想的方法,即使它經常被使用。製作尺寸爲x行的一維vector<T>會更好。然後,您可以建立索引如下(假設你按照C風格的行主要順序):

vector<mat> matrix(rows*cols); 
... 
element_ij=matrix[i*cols+j]; 

在你現在的代碼,你永遠不插入任何東西矩陣:

vector<vector<mat>> matrix; 
// In order to insert 
vector<mat> tempVec; 
tempVec[0].name = "stack"; 
vector.push_back(tempVec); 

我認爲最後一行應該是matrix.push_back(tempVec);

+0

我做了改變它應該是matrix.push_back .....所以你認爲現在它會代表二維矩陣。 – 2013-05-08 12:38:52

+0

它當然是* a *表示二維矩陣的方式。 – 2013-05-08 12:40:47

+0

那麼我怎麼知道哪一行和哪一列被訪問。這是我真正的問題。 – 2013-05-08 12:42:30