tags:

views:

44

answers:

2

Hi Guys,

How to pass a 2 dimensional Vector to a function in CPP ? I saw the examples for 1 dimension but not for 2 dimensions.

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

vector< vector<int> > matrix1(3, vector<int>(3,0)); //Matrix Declaration.
printMatrix(&matrix1); // Function call

void printMatrix(vector< vector<int> > *matrix) // Function Definition
+2  A: 

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.

casablanca
+1  A: 

Well, first of all, you're creating it wrong.

vector<vector<int>> matrix1(3, vector<int>(3,0));

You can pass by value or by reference, or by pointer(not recommended). If you're passing to a function that doesn't change the contents, you can either pass by value, or by const reference. I would prefer const reference, some people think the "correct" way is to pass by value.

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

// or
void printMatrix(vector<vector<int>> matrix);

// to call
printMatrix(matrix1);
PigBen
Don't forget a space in the nested template, i.e. `vector<vector<int> >`, otherwise some compilers will complain about invalid right shifts.
casablanca
I'll just use your comment as a note to that effect. But are there any relevant compilers where this is still an issue?
PigBen