alandalusi
alandalusi

Reputation: 1155

Passing a 2d vector into a function c++

I have a function (assign) in a class (graph) in a header file. The objective of this function is to print a 2d vector:

class Graph
{
public:
    void printvec(vector< vector<double> >&PRRMap);
};

I call this function from a cpp file such as:

Graph G;
G.printvec(vector< vector<double> > &PRRmap);

I get the following error:

error: expected primary-expression before ‘&’ token

How can I fix this?

Upvotes: 0

Views: 2055

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283893

void printvec(vector< vector<double> >&PRRMap);

This is a declaration. It includes formal parameters, each of which specifies a type and an optional name.

G.printvec(a_map);

This is a function call. It includes actual parameters, each of which is an expression, aka value. The type is not named during a function call. But you do need to specify the name of the vector you want printed.

The type of the actual parameter expression is checked against the formal parameter type specified in the function declaration. If they don't match, the compiler will look for a suitable conversion, and if it can't find one, you will get a compile error.

Since your function requires a non-const reference, most conversions will not be allowed here. You should specify the name of a suitable vector-of-vectors object that you have prepared with the data to be printed.

Upvotes: 4

Farlei Heinen
Farlei Heinen

Reputation: 5909

when you call the function you don't need the & operator

only the variable (a valid reference)

Upvotes: 3

Related Questions