我需要打印从文本文档中读取的每一行中的所有数字对。示例文本文档将是:
6 8
1 3 5
2 3 4
3 6 5
7 6 8
4 6
7 5
其中第一行是超图的网络数 (6) 和单元数 (8)。其余的行是网络中的单元格。所以网络 1 由单元格 1、3 和 5 组成,网络 2 由单元格 2、3 和 4 组成,依此类推。为了把这个网表变成一个实际的图表,我需要遍历每一行,基本上取每一行数字的所有组合。因此,在阅读第一个网络之后,我希望能够用 (1,3)、(1,5) 和 (3,5) 制作一个图表,然后沿着网表向下添加到图表中。到目前为止,我能够从文本文件中读取所有内容并打印出我放入二维数组的各个单元格。这是我的代码:
int main() {
ifstream infileHGR; // set stream for hypergraph text file
string inputFileName = "structP.hgr"; // input hypergraph filename here
infileHGR.open(inputFileName, ios::in);
clock_t start = clock(); // start clock
string line;
string data[2]; // initialize data array to take in # of nets and # of cells
int nets = 0;
int cells = 0;
// Reads in the first line of the text file to get # for nets and cells
getline(infileHGR, line);
stringstream ssin(line);
int i = 0;
while (ssin.good() && i < 2) { // error checking to make sure first line is correct format
ssin >> data[i];
i++;
}
nets = atoi(data[0].c_str()); // set first number to number of nets
cells = atoi(data[1].c_str()); // set second number to number of cells
freopen("output.txt", "w", stdout); // writes outptut to text file
// TESTING PURPOSES
cout << "Number of nets = " << nets << endl;
cout << "Number of cells = " << cells << endl;
// while loop to go through rest of the hgr file to make hypergraph (starts at line 2)
string str;
int count = 1; // counter for nets
while (infileHGR.good()) {
getline(infileHGR, str);
stringstream in(str);
int i = 0;
// have the line in str
int n = 1; // start at 1, spaces + 1 = number of nodes per net
for (int i = 0; i < str.length(); ++i) {
if (str.at(i) == ' ') {
n++; // n is number of cells in the net
}
}
// testing
//cout << "str = " << str << endl;
//cout << "n = " << n << endl;
int number;
vector<vector<int> > netList;
vector<int> temp;
while (in >> number){
temp.push_back(number);
}
netList.push_back(temp);
//printNetList(temp); // test to see if info is being put into the vectors
// loop through the 2d vector
for (const auto& inner : netList) {
cout << "net " << count << " = "; //TESTING PURPOSES
for (const auto& item : inner) {
cout << item << " ";
}
count = count + 1;
}
cout << endl;
}
clock_t stop = clock(); // end clock
infileHGR.close();
double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
printf("Time elapsed in ms: %f", elapsed);
system("pause"); //for original testing
return 0;
}
我使用向量是因为每个输入文件都有不同的大小,有些包含很多网,有些网中有多达 20 个单元。我需要帮助从网表中获取所有对(坐标)并将它们打印出来以显示所有它们。我经常使用 for 循环,但似乎无法获得有效的东西。任何帮助将不胜感激,请问我是否需要包括其他任何内容。谢谢!