How to pass 2-D vector to a function in C++?

bsoundra picture bsoundra · Oct 31, 2010 · Viewed 40.5k times · Source

If it is passed, is it passed by value or by reference?

void printMatrix(vector<vector<int>> *matrix);

...

vector<vector<int>> matrix(3, vector<int>(3,0));
printMatrix(&matrix1);

Answer

casablanca picture casablanca · Oct 31, 2010

Since your function declaration:

void printMatrix(vector< vector<int> > *matrix)

specifies a pointer, it is essentially passed by reference. However, in C++, it's better to avoid pointers and pass a reference directly:

void printMatrix(vector< vector<int> > &matrix)

and

printMatrix(matrix1); // Function call

This looks like a normal function call, but it is passed by reference as indicated in the function declaration. This saves you from unnecessary pointer dereferences.