从 2D 数组C++中提取行或列
extracting rows or columns from a 2D-array C++
>我想创建一个函数,该函数接收二维数组并将其一行("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。
有几个
错误需要先修复。
- 切勿从函数返回指向局部变量的指针。在上面的代码中,您尝试返回指向局部变量"result"内容的指针。
- 数组不能使用可变的大小声明,在您的情况下是变量列。
- 如果数组是一个二维数组,我认为这是你的意图,那么 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;
}
这将返回该行。
相关文章:
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 std::atomic 中提取指针 T<T>?
- 如何使用用户输入在C++中正确填充2D数组
- 为什么istream不支持右值提取
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何设置一个范围来提取我想要获得的信息
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 四边形的 2D 旋转
- 打印第二列时的2d字符矢量打印空间
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从 C++ 中的 3D 矩阵中提取 2D 矩阵
- 如何在 c++ 中提取 2D 数组的列?
- 从 2d 坐标的列表(矢量)中提取上限和下边界
- 从字符串流中提取到 2D 矢量
- 从 2D 数组C++中提取行或列
- 如何从2D向量中提取单行并分配给1D向量
- 从2d字符串数组中提取字符