passing a 2d array cpp
#include <iostream> #include <vector> using namespace std; typedef vector< vector<int> > Matrix; void print(Matrix& m) { int M=m.size(); int N=m[0].size(); for(int i=0; i<M; i++) { for(int j=0; j<N; j++) cout << m[i][j] << " "; cout << endl; } cout << endl; } int main() { Matrix m = { {1,2,3,4}, {5,6,7,8}, {9,1,2,3} }; print(m); //To initialize a 3 x 4 matrix with 0: Matrix n( 3,vector<int>(4,0)); print(n); return 0; }
Source: stackoverflow.com
pass 2d array to function c++
// initialize 2d array int num[3][2] = { {3, 4}, {9, 5}, {7, 1} }; // call the function // pass a 2d array as an argument display(num);
how to modify 2d array in function c++
class Array2D { private: int* m_array; int m_sizeX; int m_sizeY; public: Array2D(int sizeX, int sizeY) : m_sizeX(sizeX), m_sizeY(sizeY) { m_array = new int[sizeX*sizeY]; } ~Array2D() { delete[] m_array; } int & at(int x, int y) { return m_array[y*sizeX + x]; } };
Source: stackoverflow.com