gpt4 book ai didi

具有数组和指针的 C++ 矩阵

转载 作者:行者123 更新时间:2023-11-28 06:36:39 28 4
gpt4 key购买 nike

我有一个从文件加载矩阵的函数。现在我在将元素存储在正确位置时遇到了问题。

这是我用来存储矩阵的重要代码。此代码无法更改,因此我必须按原样使用此部分:

int **matrix
*matrix = new int[*rows * *columns];

现在我有一个 while 循环,它正在读取一个包含矩阵元素的文本文件。

但是我怎样才能将值存储在数组的正确位置呢?

通常我会在 while 循环中做这样的事情。

matrix[currentRow][currentColumn] = value;

但这在这里不起作用,因为这不是二维数组。

最佳答案

您需要将二维索引转换为一维索引。

int currentIndex = (currentRow * nColumns) + currentColumn;
matrix[currentIndex] = X; //actually (*matrix)[currentIndex] given your definition of matrix

关于具有数组和指针的 C++ 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26673903/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com