从 2D 数组C++中提取行或列

extracting rows or columns from a 2D-array C++

本文关键字:提取 2D 数组 C++      更新时间:2023-10-16

>我想创建一个函数,该函数接收二维数组并将其一行("which")作为简单数组返回。我写了这个:

int *row(int *array, int lines, int columns, int which)
{
    int result[columns];
    for (int i=0; i<columns; i++)
    {
        result[i] = *array[which][i];
    }
    return result;
}

但是,在第 7 行中,我收到以下错误:数组下标的类型"int[int]"无效。知道如何正确执行此操作吗?我还尝试将 2D 数组作为数组数组进行处理,但没有成功。我是新手,所以请避免太高级的概念。

感谢您的帮助!

更新:感谢您的帮助!现在我的代码如下所示:

int n;  //rows
int m;  //columns
int data[100][100];   
int array[100];
int *row(int *array, int rows, int columns, int which)
{
    int* result = new int[columns];
    for (int i=0; i<columns; i++)
    {
        result[i] = *array[which*columns+i];
    }
    return result;
    delete[] result;
}
int main()
{
    array=row(data, n, m, 0);
}

我仍然在main中遇到错误:将"int*"分配给"int [100]"的类型不兼容

现在可能有什么问题?我也不知道在哪里使用 delete[] 函数来释放数组。

非常感谢您的帮助!

你不能只这样做:

int result[columns];

您需要动态分配

int* result = new int[columns];

此外,您对array的使用看起来是错误的。如果array是单个指针,则需要:

result[i] = array[which*columns + i];

"array" 是一维的。你可以通过以下方式访问索引 [which][i] 的元素:array[which*columns + i]。还要删除星号,因为数组只是一个指针。

编辑:您也不能返回本地数组 - 您需要处理动态内存:

int* result = new int[columns];

然后特别注意释放此内存。另一种选择是使用 std::vector。

有几个

错误需要先修复。

  1. 切勿从函数返回指向局部变量的指针。在上面的代码中,您尝试返回指向局部变量"result"内容的指针。
  2. 数组不能使用可变的大小声明,在您的情况下是变量列。
  3. 如果数组是一个二维数组,我认为这是你的意图,那么 array[which][i] 给你一个 int。您不必取消引用它。

虽然我知道我在这里没有遵循发布礼仪,但我建议你从一本不错的教科书开始,抓住基础知识,遇到问题时来这里。

数组

的大小必须是编译时常量。

与其弄乱数组,不如使用 std::vector(可能与 2D 矩阵类一起)。

您可以使用std::vector来避免所有这些指针算术和内存分配

#include <vector>
#include <iostream>
typedef std::vector<int> Row;
typedef std::vector<Row> Matrix;
std::ostream& operator<<(std::ostream& os, const Row& row) {
  os << "{ ";
  for(auto& item : row) {
    os << item << ", ";
  }
  return os << "}";
}
Row getrow(Matrix m, int n) {
  return m[n];
}
Row getcol(Matrix m, int n) {
  Row result;
  result.reserve(m.size());
  for(auto& item : m) {
    result.push_back(item[n]);
  }
  return result;
}
int main () {
  Matrix m = {
    { 1, 3, 5, 7, 9 },
    { 2, 4, 5, 6, 10 },
    { 1, 4, 9, 16, 25 },
  };
  std::cout << "Row 1: " << getrow(m, 1) << "n";
  std::cout << "Col 3: " << getcol(m, 3) << "n";  
}
double *row(double **arr, int rows, int columns, int which)
{
double* result = new double[columns];
for (int i=0; i<columns; i++)
{
    result[i] = arr[which][i];
}
return result;
delete[] result; 
}

这将返回该行。