Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

2d

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);
like image 303
bsoundra Avatar asked Oct 30 '10 23:10

bsoundra


People also ask

How do you pass a 2 D vector in a function?

A 2D vector can be passed to the function in the same way as 1D vector, using both: Pass By Value. Pass By Reference.

How do you pass a vector to another function?

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.

Can you have 2D vectors in C++?

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


1 Answers

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.

like image 162
casablanca Avatar answered Sep 21 '22 13:09

casablanca