【问题标题】:Implementation of Adjacent Matrix with 2D vectors c++使用 2D 向量 c++ 实现相邻矩阵
【发布时间】:2013-05-08 12:29:52
【问题描述】:

我是 C++ 的初学者,我研究过向量,而不是 2D 向量。我上网很多,但互联网上的数据与 2D 矢量非常具体。 我需要在给定输入文件的情况下构建一个图,然后将 Kruskal 算法应用于最小生成树。

我的做法:

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 表示 Matrix 的哪一行或哪一列。如果它指示行,那么我怎么知道正在访问哪个列。 我的意思是vector.push_back(tempVec),将我矩阵中的哪个位置分配给数据。我知道我可以访问像 Matrix[i][j] 这样的单个元素。但是如何将权重分配给特定的行、列位置然后访问它。

您还认为克鲁斯卡尔方法会是一个很好的实现。

请在您的代码和解释中简单明了。 并提前致谢。

【问题讨论】:

标签: c++ graph vector


【解决方案1】:

使用vector&lt;vector&lt;T&gt;&gt; 是表示矩阵的一种相当次优的方式,尽管它经常被使用。最好制作一个大小为 rows x cols 的一维 vector&lt;T&gt;。然后,您可以按如下方式对其进行索引(假设您遵循 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);

【讨论】:

  • 我做了改变,它应该是 matrix.push_back .....所以你认为现在它会代表 2D Matrix。
  • 这确实是一种表示二维矩阵的一种方式。
  • 那么我怎么知道访问了哪一行和哪一列。这是我真正的问题。
  • 当您使用这种设置时,由您来定义索引方案并坚持下去。通常matrix[i][j] 指的是第 i 行第 j 列。如果你只是简单地做matrix[i],你会得到一个vector&lt;mat&gt;。您可以选择最外层的索引是指列还是行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
相关资源
最近更新 更多