假设我有一个键范围,例如0-> 1000

说0-> 99映射到一个对象
100-> 251映射到另一个
等等
等等

什么是将键映射到对象而不需要具有1000个大小的数组和一堆if(x> = 0 && x
我的意思是没有任何逻辑即阶梯表

最佳答案

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"

在您自己的类(class)中将其包装起来以隐藏细节,您可以开始了。

08-16 08:33