キーの範囲があるとします。たとえば、0 -> 1000 とします。
0 -> 99 を 1 つのオブジェクトにマップするとします。100 -> 251 を別のオブジェクトにマップします。
1000 サイズの配列と多数の if (x >= 0 && x <= 99) ビジネスを使用せずにキーをオブジェクトにマップする良い方法は何ですか?
つまり、ロジックなし、つまり階段テーブル
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"
あなた自身のクラスでそれをまとめて詳細を隠してください、そしてあなたは行ってもいいです。
おそらく、範囲のエンドポイントのみをデータ構造に保存し、それらをポイントする値にマップする必要があります。次に、[] 演算子をオーバーロードし、インデックスが収まる範囲を調べます。
データ構造があなたが説明した比率である場合、リストを使用できます(サイズを考えると、10程度の範囲が考えられます)
私はEclipseの答えが一番好きですが、範囲の開始点がターゲットの「幅」の概念を蓄積した結果である場合は、それらをベクトルに格納する方がよいでしょう。これは、範囲のセットが変更されることが予想される場合に特にうまく機能します。