假设我有一个叫做MyFunction(int myArray[][])一些数组操作的函数.
如果我像这样编写参数列表,编译器会抱怨它需要在编译时知道数组的大小.有没有办法重写参数列表,以便我可以传递任何大小的数组到函数?
我的数组的大小由static const int类中的两个s 定义,但编译器不接受类似的东西MyFunction(int myArray[Board::ROWS][Board::COLS]).
如果我可以将数组转换为向量然后将向量传递给MyFunction?是否有可以使用的单行转换或我必须手动进行转换?
AnT*_*AnT 14
在C++语言中,多维数组声明必须始终包含除第一个之外的所有大小.所以,你想做的事情是不可能的.如果不显式指定大小,则无法声明内置多维数组类型的参数.
如果需要将运行时大小的多维数组传递给函数,则可以忘记使用内置的多维数组类型.这里的一个可能的解决方法是使用"模拟的"多维数组(指向其他1D数组的指针的1D数组;或通过索引重新计算来模拟多维数组的普通1D数组).
M2t*_*2tM 12
在C++中,使用std :: vector来建模数组,除非您有使用数组的特定原因.
填充0的3x2向量的示例被称为"myArray"被初始化:
vector< vector<int> > myArray(3, vector<int>(2,0));
Run Code Online (Sandbox Code Playgroud)
传递这个结构是微不足道的,你不需要通过传递长度(因为它保持跟踪):
void myFunction(vector< vector<int> > &myArray) {
for(size_t x = 0;x < myArray.length();++x){
for(size_t y = 0;y < myArray[x].length();++y){
cout << myArray[x][y] << " ";
}
cout << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用迭代器迭代它:
void myFunction(vector< vector<int> > &myArray) {
for(vector< vector<int> >::iterator x = myArray.begin();x != myArray.end();++x){
for(vector<int>::iterator y = x->begin();y != x->end();++y){
cout << *y << " ";
}
cout << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
在C++ 0x中,您可以使用auto关键字来清理向量迭代器解决方案:
void myFunction(vector< vector<int> > &myArray) {
for(auto x = myArray.begin();x != myArray.end();++x){
for(auto y = x->begin();y != x->end();++y){
cout << *y << " ";
}
cout << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
在c ++ 0x中,for_each对lambdas变得可行
void myFunction(vector< vector<int> > &myArray) {
for_each(myArray.begin(), myArray.end(), [](const vector<int> &x){
for_each(x->begin(), x->end(), [](int value){
cout << value << " ";
});
cout << endl;
});
}
Run Code Online (Sandbox Code Playgroud)
或者基于c ++ 0x循环的范围:
void myFunction(vector< vector<int> > &myArray) {
for(auto x : myArray){
for(auto y : *x){
cout << *y << " ";
}
cout << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
*我现在不接近编译器并且没有测试过这些,请随时更正我的示例.
如果您在编译时知道数组的大小,则可以执行以下操作(假设大小为[x] [10]):
MyFunction(int myArray[][10])
Run Code Online (Sandbox Code Playgroud)
如果你需要传入一个可变长度数组(动态分配或可能只是一个需要采用不同大小的数组的函数),那么你需要处理指针.
正如对这个答案的评论所述:
boost :: multiarray可能是合适的,因为它可以更有效地建模多维数组.向量向量可能会对关键路径代码产生性能影响,但在典型情况下,您可能不会注意到问题.
将其作为指针传递,并将维度作为参数.
void foo(int *array, int width, int height) {
// initialize xPos and yPos
assert(xPos >= 0 && xPos < width);
assert(yPos >= 0 && yPos < height);
int value = array[yPos * width + xPos];
}
Run Code Online (Sandbox Code Playgroud)
这假设你有一个简单的二维数组,比如int x[50][50].