Duccio Piovani
Duccio Piovani

Reputation: 1460

Passing a multidimensional vector (matrix) to a Function in C++

I am having problems passing a multidimensonal array to a function from main. Here is an example of the problem:

double function(int**);
int main(){
    vector< vector<int> > my_vec;
    double result;
    result = funtion(my_vec); //it doesnt recognize the type. my vec
    return 0;
}
double function(int**my_vec){
    // DOES STUFF WITH THE DATA
}

What is the correct way of passing the matrix to the function?

Upvotes: 0

Views: 2903

Answers (3)

newfolder
newfolder

Reputation: 108

Std::vector is not just an array. It is STL type, whitch simulates dynamic array. What you are passing is simple 2D array like int arr[3][3]. To pass vector you need to change your function header to double function(vector< vector<int>> &vec)(or maybe double function(vector< vector<int>> vec) - depends on what you want to do)

Upvotes: 0

Useless
Useless

Reputation: 67713

The correct way to accept the argument is:

double function(vector<vector<int>> const &);

unless the function needs to modify the argument, in which case use:

double function(vector<vector<int>> &);

The int** type signature is for raw C-style arrays: there's no reason to discard the helpful C++ container here.

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

What is the correct way of passing the matrix to the function ??

Change the signature of function to:

double function(vector< vector<int> >& my_vec);

Upvotes: 4

Related Questions