c++ - 初始化二维数组 C++

标签 c++ arrays matrix

我的目标是在命令行中读入一个文件,它是一个有向图的邻接矩阵表示,并将值存储在一个二维数组中。我的计划是读取一行中的整数个数并将其用作数组的大小(即 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/

相关文章:

C++线性搜索算法,判断数组元素个数

c++ - 包含库时找不到 Qt shared_ptr

c++ - 当将预增量和后增量放在像这样的单个变量上时(++i)++,它在 c++ 中有效,但在 c 中无效

安卓.content.res.Resources$NotFoundException : String array resource ID #0x7f070002

c++ - 将此 C++ 代码转换为 Matlab

python - 从对列表中制作 Numpy 对称矩阵

c++ - 如何在现代 Opengl 中添加 View 矩阵

c++ - int **p 是什么意思?

c++ - 模板类的许多实例化会影响性能吗?

arrays - Mongoose 中的子文档数组