C++ How to make a 2D Vector function?

1.7k views Asked by At

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 :

  1. Should the 2D vector function size be initialized ?
  2. Can I change the size of gridinside the function and return a bigger 2D vector ?
  3. 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.

1

There are 1 answers

1
AresCaelum On BEST ANSWER

To answer your questions:

  1. if you are trying to loop through a vector to set its values then yes it needs to be initialized. a vector starts with 0 elements if you call the default constructor. To set the size you can call 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...
  2. Yes you can change the size of it and return a bigger vector, use .resize this won't affect your original grid since you are passing in a copy of it and not a reference to it.
  3. Yes, you can retrieve a value from a void function, if you create a reference to a variable as a parameter you can modify the value of that variable. You can read about it here: http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

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.