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
source to share
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.
source to share
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)
source to share