I have C++11 program which needs to pick a value from a range of values. Each of the ranges have an assigned value to pick a value from.
Following is my range of values with assigned values for each.
1-10 = 5
11-14 = 13
15-20 = 17
21-28 = 24
29-36 = 31
37-47 = 43
48-52 = 50
53-60 = 53
61-68 = 65
So, as you can see above 5 should be return value if the input falls between 1-10, 13 should be chosen if the input falls between 11-14 and so on.
Above requirement could be acheived with the following program with a big dirty list of if else statements.
#include <iostream>
// Following are return values to chosen based on which range the input value falls within
// 1-10 = 5
// 11-14 = 13
// 15-20 = 17
// 21-28 = 24
// 29-36 = 31
// 37-47 = 43
// 48-52 = 50
// 53-60 = 53
// 60-68 = 65
unsigned int GetValueBasedOnRange(const int value) {
int value_picked_from_appropriate_range = 0;
if (value > 1 && value < 10) {
value_picked_from_appropriate_range = 5;
} else if (value > 11 && value < 14) {
value_picked_from_appropriate_range = 13;
} else if (value > 15 && value < 20) {
value_picked_from_appropriate_range = 17;
} else if (value > 21 && value < 28) {
value_picked_from_appropriate_range = 24;
} else if (value > 29 && value < 36) {
value_picked_from_appropriate_range = 31;
} else if (value > 37 && value < 47) {
value_picked_from_appropriate_range = 43;
} else if (value > 48 && value < 52) {
value_picked_from_appropriate_range = 50;
} else if (value > 53 && value < 60) {
value_picked_from_appropriate_range = 53;
} else if (value > 61 && value < 68) {
value_picked_from_appropriate_range = 65;
}
return value_picked_from_appropriate_range;
}
int main() {
unsigned int value_within_a_range = 42;
std::cout << GetValueBasedOnRange(value_within_a_range) << std::endl;
}
Above program works fine but the big if else list of statements is bad. Also, if there are more values and ranges coming in future, they affect the if else logic. Is there way in C++ 11 that I could set up a nice static look up table to achieve this without having to write if else? Some static table that I could declare in a header file with the output values in there?
Some smart way of doing this in C++11? I can probably try an std::map<std::pair<unsigned int, unsigned int>, unsigned int>
? But, wondering of a nice way using that or an even simpler approach..
PS: I am not sure if its called a look up table or something else. But, something that picks a hard coded value for a certain pair/range of values.
Aucun commentaire:
Enregistrer un commentaire