如何正确接受平方加权邻接矩阵
How do you properly accept a square weighted adjacency matrix?
我正在尝试重新创建Kruskal和Prim的算法。为此,我需要输入一个加权邻接矩阵。
加权邻接矩阵的示例输入为:
0 0 355 0 695 0 0 0
0 0 74 0 0 348 0 0
355 74 0 262 0 269 0 0
0 0 262 0 0 242 0 0
695 0 0 0 0 151 0 0
0 348 269 242 151 0 83 306
0 0 0 0 0 83 0 230
0 0 0 0 0 306 230 0
这些数字已经过少量编辑,以提供更清晰的信息。每个数字之间应该有一个空格。
至于接受这些值并记录它们,我可以使用以下代码接受其中的一行:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string temp;
string buf;
vector<string> matrix;
cout << "Matrix: ";
getline(cin, temp);
stringstream ss(temp);
while(ss >> buf)
{
matrix.push_back(buf);
}
for(int i = 0; i < matrix.size(); i++)
{
cout << matrix[i] << " ";
}
cout << endl;
return 0;
}
示例输出:
Matrix: 0 0 355 0 695 0 0 0
0 0 355 0 695 0 0 0
关于我的问题,我怎样才能要求正确数量的矩阵行并记录所有矩阵行?
在示例中,我将如何要求另外 7 行矩阵值(在接受值之前不需要 cout/cin 语句(?
让我们将
您已经拥有的内容提取到一个函数中:
std::vector<std::string> read_row(std::istream & is)
{
string line;
string number;
vector<string> row;
getline(is, line);
stringstream ss(line);
while(ss >> number)
{
row.push_back(number);
}
return row;
}
现在我们可以多次执行此操作
int main()
{
std::vector<std::vector<std::string>> matrix;
std::vector<std::string> first_row = read_row(std::cin);
matrix.push_back(first_row);
// We already have the first line, so loop from 1
for (int i = 1; i < first_row.size(); ++i)
{
std::vector<std::string> next_row = read_line(std::cin);
if (next_row.size() != first_row.size())
{
std::cout << "Row " << i << " does not match length";
return 1;
}
matrix.push_back(next_row);
}
return 0;
}
现在您可能想使用这些数字进行计算,因此您可以使用 int
或 double
代替std::string
。ss >> number
是格式化输入,因此它会为您将文本转换为数字。
相关文章:
- 如何在C++中为表面制作邻接矩阵
- 在 c++ 中初始化邻接矩阵
- 有关邻接矩阵实现的问题
- MFC:在编辑框中表示邻接矩阵
- C++中有向无环图的邻接列表到邻接矩阵的转换
- 我需要将阵列样式的邻接矩阵转换为矢量样式(以使其看起来更好)
- 如何正确接受平方加权邻接矩阵
- 创建随机邻接矩阵,每个节点具有最小'k'度
- 如何在C++中将边列表转换为邻接矩阵,其中包含连接到顶点的边数而不是一条边?
- 确定邻接矩阵是否具有周期,然后输出该周期
- 邻接矩阵构建功能用一些图崩溃
- 使用邻接矩阵获取给定节点的所有边缘
- 对邻接矩阵最大循环中的节点进行计数
- 图实现,使用邻接矩阵,在链接中带有自定义数据
- 在C++中向邻接矩阵的边添加代价
- 邻接矩阵上的BFS
- 查找路径的有向图邻接矩阵
- 如何在c++中使用模板图类中的向量创建邻接矩阵
- Dijksta算法在邻接矩阵中找不到路径
- 什么是快速矩阵或二维数组,用于在C++中存储邻接矩阵