多维数组
Multi-dimensional array
本文关键字:数组 更新时间:2023-10-16
我需要创建一个函数,该函数具有一个参数,该参数是一个由用户指定的二维多维数组,例如
int function(int a, int b, int array[a][b])
{
...
}
我该如何在C++中做到这一点?
编译时维度是否已知?在这种情况下,将它们转换为模板参数,并通过引用传递数组:
template<int a, int b>
int function(int(&array)[a][b])
{
...
}
示例客户端代码:
int x[3][7];
function(x);
int y[6][2];
function(y);
假设在编译时维度未知,则用一维数组模拟二维数组:
int& getat(int x, int y, int r, int c, int *array) {return array[y*c+x];}
int function(int a, int b, int *array) {
getat(4, 2, a, b, array) = 32; //array[4,2] = 32
}
或者,为了安全起见,将其全部封装在一个类中:
template <class T>
class array2d {
std::vector<T> data;
unsigned cols, rows;
public:
array2d() : data(), cols(0), rows(0) {}
array2d(unsigned c, unsigned r) : data(c*r), cols(c), rows(r) {}
T& operator()(unsigned c, unsigned r) {
assert(c<cols&&r<rows);
return data[r*cols+c];
}
};
或者,最好使用Boost的多维数组,这将比普通人写的任何东西都要好。
我不确定这是否有效,因为你的问题和代码不一样,根据你的代码,函数可以有3个参数,所以这会有效:
int function(int a, int b, int** &array)
{
array = new int*[a];
for (int i =0;i<a;i++)
array[i] = new int[b];
// I don't know why you are returning int, probably doing something here....
}
然而,您的问题表明,您的函数只能接受一个参数,因此:
- 如果维度在编译时已知,那么Fred的答案是最好的(事实上它迷住了我!:))
- 如果没有,除了将所有这些值封装在一个对象中之外,我看不到任何可能的解决方案允许传递多个用户指定的值
像这样:
class Foo {
public:
Foo(int d1, int d2)
{ a = d1; b = d2; }
int a,b;
int** array;
};
int function(Foo &f)
{
f.array = new int*[f.a];
for (int i = 0;i<f.a;i++)
f.array[i] = new int[f.b];
// I don't know why you are returning int, probably doing something here....
}
虽然我觉得这是个坏主意,但事实上function
可以是一个无参数的方法:
class Foo {
public:
Foo(int d1, int d2)
{ a = d1; b = d2; }
void Create() // Or could do this right in the Constructor
{
array = new int*[a];
for (int i = 0;i<a;i++)
array[i] = new int[b];
}
private:
int a,b;
int** array;
};
尽管如此,这还是一个坏主意,因为你正在重新发明轮子,因为STL中有一个完美的类可以为你做所有的工作:
vector< vector<int> > v; // Now v is a 2D array
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '