views:

192

answers:

4

Hello, I need a data structure with the following properties:

  • Access to elements must be very fast
  • Elements, that are not added, shouldn't take memory (as ideal, size of empty structure near to zero)
  • Each element has two integer coordinates (x,y) (access to elements only by them)
  • Max count of elements known at creation time (over 10^3)
  • Element contains few float values

It would be good if you also directed to an implementation of this structure in C or C++.

+7  A: 

Are you looking for a sparse matrix ?

Victor Nicollet
Good point. Except that, if the OP's remark "over 10^3" really means "a few thousand", I'd recommend a simple 2-d array.
larsmans
+1  A: 

If your X and Y are relatively small then a two dimensional array of pointers would work. 10000 pointers would be 40K in 32 bit code.

Romain Hippeau
Even in 64 bit mode, he can used 32 bit indexes.
Amigable Clark Kant
+3  A: 

Check this out - you could alter the element type to float if this does everything you want.

Concise Sparse Matrix Package in C

For C++ you could use Boost.uBLAS - sparse_matrix details here.

Steve Townsend
+1  A: 

 

typdef ElementAccessor std::pair<int, int>;

struct Element
{
  float f1;
  float f2;
  //etc.

};

std::map< ElementAccessor, Element > myElementMap;

You can now use this map as a matrix. ElementAccessor refers to x,y. Just make sure to see if the element exists in the map before you try to access it, or one is created by default.

http://www.cplusplus.com/reference/std/utility/pair/ http://www.cplusplus.com/reference/stl/map/find/

edit: the template brackets are showing up for the map. the map key type is ElementAccessor, the value is Element. Also, for the pair, the templating is int, int.

San Jacinto
Accesss to these elements is logarithmic time. So if you put 1 million elements in the map, it still would not take many operations to access your data. Not a constant-time array dereference, but a big space-saver.
San Jacinto
@San: markup fixed. There is (or used to be, I didn't check) an irritating bug in SO that code indentation doesn't work on the first line, hence the nbsp.
Steve Jessop
@steve thank you!
San Jacinto