我正在尝试重新创建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语句)?
答案 0 :(得分:0)
让我们将你已经拥有的东西提取到一个函数中:
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;
}
现在您可能希望使用这些数字进行计算,因此您可以使用std::string
或int
代替double
。 ss >> number
是格式化输入,因此它会将文本转换为数字。