2D vector pass to function

i found that my 2D vector's value is not changed after i use the function "test".
i pass the maze by "hahaha(maze)"

the following are parts of the code.

ps. my english is bad, so please ask me if you can't understand what i want to ask

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  vector< vector<int> > maze(sizey, vector<int>(sizex));
	
	for(int i=0; i<sizey;i++)
	{
		for(int j=0;j<sizex;j++)
		{
			maze[i][j]=1;
			
	        if(i==0||i==1||j==0||j==1||i==-1+maze.size()||i==-2+maze.size()||j==-1+maze[0].size()||j==-2+maze[0].size())
         	{
		        maze[i][j]=2;			    
	        }
		}
	}
  

 void test(vector<vector<int> > maze) 
{
       maze[3][2]=0;
       maze[3][3]=0;
       maze[3][4]=0;
       maze[3][5]=0;
       maze[4][5]=0;
       maze[5][5]=0;
}



   
Last edited on
Arguments are passed by value by default which means that the function receives a copy of the argument that you passed to the function. Making changes to the copy will not have any effect on the original object.

If you want the function to be able to manipulate the passed vector you can change the function so that the vector is passed by reference, like this:
1
2
3
4
5
6
7
8
9
void test(vector<vector<int> >& maze) 
{
       maze[3][2]=0;
       maze[3][3]=0;
       maze[3][4]=0;
       maze[3][5]=0;
       maze[4][5]=0;
       maze[5][5]=0;
}


Passing large objects like std::vector by reference is usually a good idea even if you don't want to manipulate the vector because it avoids copying the vector so it is more efficient. To avoid that the vector is accidentally modified inside the function you can pass it as a const reference.
1
2
3
4
5
6
7
8
9
10
11
void print(const vector<vector<int> >& maze) 
{
	for (size_t y = 0; y < maze.size(); ++y)
	{
		for (size_t x = 0; x < maze[y].size(); ++x)
		{
			std::cout << maze[y][x] << ' ';
		}
		std::cout << std::endl;
	}
}
Last edited on
Your test() takes 'maze' by value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void foo (int x) { x = 7; }

void bar()
{
  int y = 42;
  foo( y );
  cout << y;
}

// Lets "pseudo-inline" the code of foo into bar.
// This is equivalent to the one above:
void bar()
{
  int y = 42;
  int foo_x = y;
  foo_x = 7;
  cout << y;
}

Pass a reference to the vector.
1
2
3
4
5
6
7
8
void foo (int & x) { x = 7; }
// Pseudo-inline with the new foo:
void bar()
{
  int y = 42;
  y = 7;
  cout << y;
}

Last edited on
Topic archived. No new replies allowed.