查找表,其中大多数顺序值指向同一个对象?

Dev*_*Dev 2 c++ algorithm lookup

假设我有一系列键,比如0 - > 1000

假设0 - > 99映射到一个对象100 - > 251映射到另一个对象等.

将键映射到对象的好方法是什么,而不必拥有1000个大小的数组和一堆if(x> = 0 && x <= 99)业务?

我的意思是没有任何逻辑,即一个阶梯台

Ecl*_*pse 10

使用std::map连同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"
Run Code Online (Sandbox Code Playgroud)

将它包装在你自己的课堂中以隐藏细节,你就可以去了.