1

I need to store some numbers like this

key => (four integers, between 0 to 30 (maxmimum), -1 means NULL)
125 => (1,3,5,20)
80 => (4,2,-1,-1)
20 => (10,12,21,3)
...

I need the fastest random access. Actually it is going to be a table of data for my application. I thought of storing these values inside a header and call them where ever I need. I mostly do scripting (PHP/Python) and there I have Arrays/Dictionaries. But what about C++?

I have found map and unordered_map (which seems the former is better for random access) so far.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
vfsoraki
  • 2,186
  • 1
  • 20
  • 45

1 Answers1

2

You could use a std::unordered_map to hold this, ie: std::unordered_map<int, std::array<int, 4>>.

The use of unordered_map will provide faster access by key. From this documentation:

unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Yes, that documentation was the first when I googles, but I was wondering if there is another way I am missing. I will accept this answer and use it sometime later, if no one has another suggestion. BTW, can anyone give me a code example for unordered_map? I read somewhere that it need hashing function and I have to build it. – vfsoraki Oct 29 '13 at 17:49
  • 1
    @thelastblack If you're using an int as a key, you won't need a custom hashing function. Usage is pretty simple - see: http://stackoverflow.com/a/2179985/65358 for an example – Reed Copsey Oct 29 '13 at 17:51
  • Great! I'm going for it. ThanQ! – vfsoraki Oct 29 '13 at 17:54