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);
A 2D vector can be passed to the function in the same way as 1D vector, using both: Pass By Value. Pass By Reference.
When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By value. Pass By Reference.
Initializing 2D vectors in C++Each value inside the first set of braces, like '{1, 0, 1}' and '{0, 1}' are vectors independently. Note: To create 2D vectors in C++ of different data-type, we can place the data-type inside the innermost angle brackets like <char> .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With