I'm trying to create a function in C++ that returns a 2D vector. The function also has a 2D vector as argument, the idea would be to return a modified version of this 2D vector, with the function.
I won't put my whole code here as is would be totally off the question, but to sum up the function looks like this :
using std::vector;
vector<vector<char> > function(vector<vector<char> > grid) {
int width = static_cast<int>(grid.front().size());
int height = static_cast<int>(grid.size());
for(int y=0; y < height; ++y)
{
for(int x=0; x < width; ++x)
{
grid[y][x]= 'H';
}
}
return grid;
}
And I would then do in the main :
vector<vector<char> > new_grid = function(grid);
But it doesn't work in the way I'm using it, so I have a few questions :
- Should the 2D vector function size be initialized ?
- Can I change the size of
grid
inside the function and return a bigger 2D vector ? - And, it might be a dumb question but, is it actually possible to retrieve a value, an array, a string, in a function without using return, in a void function ?
Thanks for your help !
I can show my whole code if you want but it is quite big and might not be so clear.
To answer your questions:
grid.resize(new_size)
, now all the vectors inside of your grid also have a size of zero so you can loop through grid and resize all of those....resize
this won't affect your original grid since you are passing in a copy of it and not a reference to it.If you aren't changing the original grid, it might be a good idea to pass it by const reference so you aren't making so many copies.