将2D数组传递到功能
Pass 2D array to function
我是编程的新手。
用户将输入2D数组的大小,然后我想将此数组传递给功能。我该怎么做?
有两种方法可以实现您的目标。
第一种方法正在使用动态分配的C风格数组。除非您被迫支持现有代码,否则您不应在C 中这样做。但是在这种情况下,最好考虑重构。
第二路正在使用std::vector
。此类将低级操作封装在记忆中。它会使您摆脱许多潜在的错误。
要向您展示std::vector
的优势,我已经编写了两个程序。他们输入2D数组的大小(另一种方式称为矩阵)并创建它。
使用C风格阵列创建矩阵,请求大量的代码和指针。为了简单起见,以下代码无法处理异常。在实际代码中,您应该这样做以避免内存泄漏,但是代码会变得更加困难。
#include <iostream>
#include <cstddef>
using namespace std;
void function(int** matrix, size_t nrows, size_t ncols)
{
}
int main()
{
size_t nrows;
size_t ncols;
cin >> nrows >> ncols;
// allocate memory for matrix
int** matrix = new int*[nrows];
for (size_t i = 0; i < nrows; ++i)
matrix[i] = new int[ncols];
function(matrix, nrows, ncols);
// release memory
for (size_t i = 0; i < nrows; ++i)
delete[] matrix[i];
delete[] matrix;
}
因此,在C 中,使用std::vector
会更容易。由于std::vector
是一类,因此具有构造函数和驱动器封装分配和释放内存。
#include <iostream>
#include <vector>
using namespace std;
void function(vector<vector<int>>& matrix)
{
}
int main()
{
size_t nrows;
size_t ncols;
cin >> nrows >> ncols;
// create matrix
vector<vector<int>> matrix(nrows);
for (size_t i = 0; i < nrows; ++i)
matrix[i] = vector<int>(ncols);
// you don't even need to pass sizes of matrix
function(matrix);
// automatically called destructor of matrix releases memory
}
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 带内存和隔离功能的SQLite
- 如何使用用户输入在C++中正确填充2D数组
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 通过功能进行2D矢量输入和显示
- 借助功能将 2D 转换为 1D 数组
- 将 2D 数组传递给大小为变量的功能
- C++的新增功能:创建 2D 数组并具有正确的赋值运算符:分割错误
- 将2D数组传递到功能
- 使用键盘功能修改C GLUT中的2D数组指针
- C 2D数组功能
- 我不能在不使用指针的情况下返回 2d 数组!我正在制作一个井字游戏类型游戏,这是我的向上移动功能
- 井字游戏 BIG 板使用功能和 2D 阵列
- c++ 2d array显示功能
- std::map唯一 std::less<> 2D 点作为键的功能
- 使用OpenGL固定功能旋转和平移2D图像