Guillaume Leseur Guillaume Leseur - 13 days ago 8
C++ Question

Passing a 2d vector to a function

I have a 2d vector of integers :

std::vector<std::vector<int> > matrix;


And I want to call a function on this object.
The function is :

int coverTransactions(int k, const std::vector<std::vector<int> > matrix ) { //k nombre de clusters
int compteur = 0;
for(int t = 0; t != 11; t++) {
compteur = 0;
for(int i = 0; i != k; i++) {
if(matrix[t][i] == 1)
compteur++;
}
if(compteur != 1)
return -1; //on retourne -1 si la transaction n'appartient pas à un et un seul cluster
}
return 0;//si tout se passe correctement, cad t appartient à un et un seul cluster on retourne 0
}


Don't pay attention to the French comments, it's just to explain how returning values are linked to the problem I want to solve but it doesn't affect the understanding of the code ...

For some reason, when calling the function this way :

std::cout << coverTransactions(3, &matrix) << std::endl;


I get the following error :

coderror: cannot convert ‘std::vector<std::vector<int> >*’ to ‘int (*)[3]’ for argument ‘2’ to ‘int coverTransactions(int, int (*)[3])’


I don't understand why because they are the same type ...

Answer

The thing happening here is a pass by reference, which is different from pass by pointer, where you pass the address of a variable into a function (when calling it) and the function's definition accepts a pointer. Here, you are basically passing a pointer to the vector as an argument and thus doing a pass by pointer :

coverTransactions(3, &matrix)

, whereas according to your function's definition, a pass by reference is happening here, hence, simply pass the vector as it is in the function :

coverTransactions(3, matrix)

The difference between the above two methods are that a pointer can be NULL, but references are never NULL, and hence we are sure that we are referencing a valid variable. That's why it's a good practice to use references whenever you can, and use pointers only when you have to.