Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to move row/column in 2D std::vector

I'm creating game application in C++. I have map represented as 2-dimensional std::vector of Tile objects.

I need to update that map as player moves. From server application I get row or column with a new part of global map, which should be placed in local client's map, for example:

enter image description here

In a figure 1 there's a local map before player moves. Top row is filled with objects 1, center with 2 and bottom with 0. Now when player moves up, I get new top row filled with objects 3 and all the others should go down, and the previous bottom row should disappear.

I can do it just by moving required objects in for loops, but I was thinking if there's already some kind of algorithm in standard library or prefered by many, efficient way to achieve this kind of modifications.

EDIT:

Sorry I didn't realize that there would a difference between doing this operation for row and for column, but indeed there is. So I also editted my title, because I sometimes need to do it for column too.

like image 764
dziwna Avatar asked Apr 25 '13 09:04

dziwna


1 Answers

You might want to implement an iterator and don't move the elements of the vectors at all. Simply define a variable for the index of the top row (on the screen), then use the modulo operator to iterate over all the rows (so only the 000 row should be overwritten with 333, and the top row index will be 2 instead of 0). This algorithm is effecient (only as many memory writes as needed), and could be used to scroll in any direction:

  • Moving upwards: decrement the top row index (mod row number), change the last row
  • Moving downwards: increment the top row index (mod row number), change the first row
  • Moving left: decrement the left col index (mod col number), change the last col
  • Moving right: increment the left col index (mod col number), change the first col.
like image 79
WebMonster Avatar answered Nov 21 '22 19:11

WebMonster