在 C++ 中使用 std::vector 对数组建模,除非您有使用数组的特定原因。
一个填充为 0 的 3x2 向量被初始化为“myArray”的示例:
vector< vector<int> > myArray(3, vector<int>(2,0));
传递这个结构是微不足道的,你不需要搞砸传递长度(因为它会跟踪):
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;
}
}
您也可以使用迭代器对其进行迭代:
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;
}
}
在 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;
}
}
在 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;
});
}
或者c++0x中基于范围的for循环:
void myFunction(vector< vector<int> > &myArray) {
for(auto x : myArray){
for(auto y : *x){
cout << *y << " ";
}
cout << endl;
}
}
*我现在不在编译器附近,也没有测试过这些,请随时纠正我的例子。
如果您在编译时知道数组的大小,则可以执行以下操作(假设大小为 [x][10]):
MyFunction(int myArray[][10])
如果你需要传入一个可变长度数组(动态分配或者可能只是一个需要不同大小数组的函数),那么你需要处理pointers。
并且作为这个答案状态的cmets:
boost::multiarray 可能是合适的,因为它可以更有效地建模多维数组。向量向量可能会对关键路径代码的性能产生影响,但在典型情况下,您可能不会注意到问题。