2

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

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

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

我的意思是没有任何逻辑,即阶梯表

4

3 回答 3

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"

将其包装在您自己的课程中以隐藏细节,您就可以开始了。

于 2009-09-24T04:16:30.707 回答
2

您可能应该只将范围的端点存储在数据结构中,并将它们映射到它们指向的值。然后重载 [] 运算符并让它查找索引适合的范围。

您可以使用列表,如果数据结构符合您描述的比例(10 个左右可能的范围,给定它们的大小)

于 2009-09-24T04:05:34.637 回答
1

我最喜欢 Eclipse 的回答,但是如果范围的起点是累积目标“宽度”的某些概念的结果,那么最好将它们存储在向量中。如果您期望范围集发生变化,这将特别有效。

于 2009-09-24T04:25:29.440 回答