Insert at specific location of a 2d vector

2019-08-25 06:26发布

问题:

I have a 2d vector which represents a 2d grid; so grid[0][2] for example. I am needing to 'insert' -might not be the right word here. a vector at a specific location say grid[3][2] there will definitely be a grid[0][0] but when im needing to insert into grid[3][2] there may be nothing before it other than grid[0][0] and there needs to be the space in between for later on. Is there any way to do this?

Thank you for your help.

ps: I should note that the size of the vectors are not known (they will grow over time)

回答1:

I'm not sure if I understand your requirements correctly, but:

std::vector<std::vector<int>> grid(4);  // 4 rows

grid[3].resize(3)  // resize 4th row

grid[3][2] = 42;

Your 2D grid would then "look" like that:

 |
 - 
 |
 -                  <---  3 empty rows
 |
 --------------
 | 0 | 0 | 42 |
 --------------

You can freely resize the rows later on. Note that there is row 0, but no [0][0] element just yet, you have to add it yourself.



标签: c++ vector