A lookup table where most consecutive values ​​point to the same object?

Suppose I have a range of keys, say 0 -> 1000

Say 0 β†’ 99 for one object 100 β†’ 251 cards for another, etc. and etc.

What is a good way to map a key to an object without having to have an array of size 1000 and an if (x> = 0 && x <= 99) business relationship?

I mean without any logic, i.e. stairstep tables

+2


source to share


3 answers


Use std::map

with lower_bound

:

map<long, string> theMap;
theMap[0] = "lessThan1";
theMap[99] = "1to99";
theMap[1000] = "100to1000";
theMap[numeric_limits<long>::max()] = "greaterThan1000";
cout << theMap.lower_bound(0)->second << endl; // outputs "lessThan1"
cout << theMap.lower_bound(1)->second << endl; // outputs "1to99"
cout << theMap.lower_bound(50)->second << endl; // outputs "1to99"
cout << theMap.lower_bound(99)->second << endl; // outputs "1to99"
cout << theMap.lower_bound(999)->second << endl; // outputs "100to1000"
cout << theMap.lower_bound(1001)->second << endl; // outputs "greaterThan1000"

      



Wrap it in your own class to hide the details and you're good to go.

+10


source


You should probably only store the endpoints of the range in your data structure and map them to the specified value. Then overload the [] operator and find the range in which the index fits.



You can use a list if the data structure has the specified proportions (10 or so possible ranges given their size)

+2


source


I love that Eclipse responds the best, but in cases where the starting point of the range is due to the accumulation of some notion of "width" targets, you're probably better off just storing them in a vector. This will work especially well if you are expecting a range change.

+1


source







All Articles