Search code examples
c++vector2d

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


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);

Solution

  • 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.