初始化二维数组 C++
Initializing a 2D Array C++
我的目标是在命令行读取文件,该文件是有向图的邻接矩阵表示,并将值存储在二维数组中。我的计划是读取一行上的整数数量并将其用作数组的大小(即 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];
给我一个错误,说"计数"大小参数应该是一个常量。我计算输入大小的方式是否使用无效的方式,或者有没有办法创建一个常量用作我的大小参数?
考虑使用向量向量,而不是使用 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;
}
}
您将
需要使用动态数组
int *myArray; //Declare pointer to type of array
myArray = new int[x]; //use 'new' to create array of size x
myArray[3] = 10; //Use as normal (static) array
...
delete [] myArrray; //remeber to free memeory when finished.
http://www.cplusplus.com/forum/beginner/1601/
http://www.cplusplus.com/doc/tutorial/dynamic/
你不会得到一个二维数组。您将必须使用数组数组。
如果您愿意使用动态分配,请执行如下操作:
int *myArray = new int [count]; // variable length array can get you into trouble here,
// if you are not careful as the inner dimension needs
// to be freed before the array goes out of scope.
for (/*iterate from 0 count*/) {
myArray[i] = new int [count];
}
myArray[m][n] to give you a semblance of what you wanted.
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中动态二维数组的访问冲突
- 遍历二维数组的所有子数组
- 将二维数组的所有元素插入到一维数组中
- 在函数中传递二维数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 创建 std::string 的二维数组的最佳做法
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 元素在二维数组 c++ 中的出现次数
- 执行 c++ 二维数组
- C++ 中的二维数组初始化为一个值
- 在C++中初始化第一维大小未知的二维数组
- 如何在二维数组中存储值?