传递 2D 数组 c++
Passing 2d array c++
我正在尝试制作一个交换两列的小程序,我必须使用函数才能做到这一点,但我刚刚开始使用 c++,我无法理解我做错了什么。
#include <iostream>
using namespace std;
int colSwap(int ng, int ns, int pin[][ns]) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
cout << " i:" << i << " j:" << j << " " << pin[i][j] << " " << endl;
}
cout << endl;
}
}
int main() {
int ng = 3;
int ns = 4;
int pin[3][ns] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
colSwap(ng,ns,pin);
return 0;
}
我知道这样写
int colSwap(int pin[][4]) {
}
但我需要另一种方法
虽然可以在 C 中传递这样的大小,但在 C++ 中是不可能的。原因是C++没有可变长度数组。C++ 中的数组在编译时必须固定其大小。不,将大小参数设为const
不会使它们成为编译时常量。
我建议您改用std::array
(或可能的std::vector
)。
您可以使用模板函数
#include <iostream>
using namespace std;
template <size_t R, size_t C>
void colSwap(int(&arr)[R][C]) {
for (int i = 0; i < R; ++i) {
for (int j = 0; j < C; ++j) {
cout << " i:" << i << " j:" << j << " " << arr[i][j] << " " << endl;
}
cout << endl;
}
}
int main() {
const int ng = 3;
const int ns = 4;
int pin[ng][ns] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
colSwap(pin);
return 0;
}
声明数组时,它的大小必须是固定的,所以ng
和ns
应该是const int
的。pin
的类型实际上是int[3][4]
,你可以只传递这种类型的引用,让编译器推断出大小。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '