我的目标是在命令行中读入一个文件,它是一个有向图的邻接矩阵表示,并将值存储在一个二维数组中。我的计划是读取一行中的整数个数并将其用作数组的大小(即 5 行输入,每行 5 个整数意味着我将创建一个 5 x 5 数组)。但是,要初始化一个数组,需要一个常量值,并且计算每行的整数并将其存储在一个变量中以用作我的大小参数,这不允许我创建数组。
示例输入:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
代码:
#include <iostream>
#include <sstream>
#include <fstream>
using namespace std;
int main(int argc, char **argv)
{
string currentLine;
int i, m = 0;
int count;
ifstream input(argv[1]);
int storage[10000];
printf("Original matrix: \n" );
if(input.is_open())
{
while(getline(input, currentLine))
{
istringstream iss(currentLine);
count = 0;
while(iss >> i)
{
if(iss.eof())//at end of each line, ends loop
{
count++;
storage[m] = i;
m++;
printf("%d \n", i);
break;
}
else
{
count++;
storage[m] = i;
m++;
printf("%d ", i);
}
}
}
}
int **matrix;
matrix = new int*[count];
for(int y = 0; y < count; y++)
matrix[y] = new int[count];
for(int r = 0; r < count; r++)
for(int c = 0; c < count; r++)
matrix[r][c] = storage[r+c];
printf("first = %d ", matrix[0][0]);
system("PAUSE");
return 0;
}
根据我的输入,我应该创建一个 5 x 5 的数组。但是线路
int matrix[count][count];
给我一个错误,说“计数”大小参数应该是一个常数。我计算输入大小的方法是否使用了无效的方法,或者是否有办法创建一个常量用作我的大小参数?
最佳答案
考虑使用 vector 的 vector ,而不是使用 2D 原生 C++ 数组。
#include <vector>
#include <iostream>
int main() {
using namespace std;
int count = 5;
// create a matrix of 'count' rows by 0 columns
vector<vector<int>> matrix(count);
// resize the column count for each row
for (auto& r : matrix)
r.resize(count);
// use it just like an array
for (int i = 0; i < count; ++i)
matrix[i][i] = i;
for (int r = 0; r < count; ++r) {
for (int c = 0; c < count; ++c)
cout << matrix[r][c] << ' ';
cout << endl;
}
}
关于c++ - 初始化二维数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392068/