简体   繁体   English

用2D向量实现相邻矩阵C ++

[英]Implementation of Adjacent Matrix with 2D vectors c++

I am a beginner in c++ and I have worked on vectors just not on 2D vectors. 我是C ++的初学者,我从事过矢量方面的工作,而不是2D矢量。 I have surfed a lot, but data on internet is very specific related to 2D vectors. 我已经冲浪了很多,但是互联网上的数据与2D向量非常相关。 I need to build a graph given an input file and then apply Kruskal's algorithm for minimum spanning tree. 我需要构建一个给定输入文件的图形,然后将Kruskal算法应用于最小生成树。

My approach: 我的方法:

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 .......

. . . . Now I am trying something like this: 现在,我正在尝试这样的事情:

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

Now I have no idea that when I do tempVec[0].name , 0 indicates which row or col of Matrix. 现在我不知道当我执行tempVec[0].name ,0指示矩阵的哪一行或哪一列。 If it indicates row then how do I know which col is being accessed. 如果它指示行,那么我怎么知道正在访问哪个列。 I mean vector.push_back(tempVec) , assigns which position in my Matrix to data. 我的意思是vector.push_back(tempVec) ,将矩阵中的哪个位置分配给数据。 I know I can access individual elements like Matrix[i][j]. 我知道我可以访问Matrix [i] [j]等单个元素。 But How can I assign weight to a particular row, col position and then access it. 但是,我如何为特定的行分配权重,列的位置然后访问它。

Further do you think will be a good implementation for Kruskal's Method. 此外,您认为这将是Kruskal方法的良好实现。

Please be simple in your code and explanatory. 请简化您的代码并进行说明。 And thanks in advance. 并预先感谢。

Using vector<vector<T>> is a fairly suboptimal way to represent matrices, even though it is often used. 使用vector<vector<T>>是表示矩阵的一种次优方法,尽管它经常被使用。 It would be better to make a one-dimensional vector<T> of size rows x cols. 制作大小为x cols的一维vector<T>会更好。 You can then index it as follows (assuming you follow C-style row major ordering): 然后,您可以按如下所示对其进行索引(假设您遵循C样式行的主要顺序):

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

In your current code, you never insert anything into matrix: 在当前代码中,您永远不会在矩阵中插入任何内容:

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

I assume the last line should be matrix.push_back(tempVec); 我假设最后一行应该是matrix.push_back(tempVec); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM