vectors of vectors in functions

Hi there,
I want to pass a matrix as an argument of a function, and instead of using multidimensional arrays or pointers to pointers my teacher told me to use vectors of vectors. the code is something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

using namespace std;

void example(vector <vector <double> > &v1, vector <vector <double> > &v2, int N)
{
for(int i = 0; i < N+2; i++)
	{
		for(int j = 0; j < N+2; j++)
		{
			v1[i][j] = 2.0;	
                        v2[i][j] = v1[i][j];	
                }
       }
}


and then on the main function:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{

int N;
cin >> N;

vector <vector <double> > v1(N+2);    //here I declare the two matrixes
vector <vector <double> > v2(N+2);

example(v1, v2, N);

return 0;
}


but I get the following errors:

referred to line 10 in the main:
error: invalid initialization of reference of type ‘std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >&’ from expression of type ‘double’

and, referred to line 6 in the first part of the code:
error: in passing argument 2 of ‘void init_guess(std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >&, std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >&, int)’

What do these errors mean?

P.S. this is not the whole of my program but it's the part that is giving me errors.

You should show relevant code. In the error message there is function name void init_guess not void example
that compiles fine, but your v1 and v2 are vectors of N+2 empty vectors, and the first v1[i][j] is an error.

Change your v1 and v2 in main to

1
2
vector <vector <double> > v1(N+2, vector<double>(N+2) );
vector <vector <double> > v2(N+2, vector<double>(N+2) );


Also, vectors know their size, so passing N to your function is redundant.
Last edited on
I checked the real code of the program and I only made an error in calling the function..
Thanks!
Topic archived. No new replies allowed.