direct access to vector elements similar to arrays
I'm currently creating a tile based game, where elements of the games are placed in four different vectors (since there are multiple game objects with different properties, hence stored in different vectors).
These game elements themselves contain x and y coordinates similar to how they are stored in a two dimensional array. i was wondering if there was a way to access these vector elements similar to two dimensional array access (currently i am implementing an for开发者_如何学C loop to cycle the elements while comparing its coordinates).
This kinda sucks when i need to refresh my display at every game cycle (since the large number of comparisons and loops).
I'm implementing this in java btw.
My recommendation would be to think "object-oriented": create a class named Board or Grid or whatever fits that encapsulates that implementation detail of choosing between 2D array or Vector of Vectors. Add a method that lets you return a board token for a given (i, j) index into the board.
Don't use Vector, use ArrayList.
If you have very large datas, see perhaps buffers, for instance IntBuffer.
Three Ideas:
- You could use a HashMap with the coordinates as key and your elements as value. This is faster than cycling through the vector and lightweight for memory.
- You could store null instead of elements at empty coordinates. This way you can access each stored memory by its coordinates.Fastest but memory intensive way.
- A speed up for what you currently do: Sort your elements by their coordinates once and then use binary search to find them in the vector.
精彩评论