Is it possible to do enum like below
enum {
10 poor
100 rich
1000 very_rich
}
so that when i do search by input value let say 101. it will return “rich” ? how to do this in enum? can give example? i do not want to loop entire enum with forloop to get the string_value. possible?
Use an
enumwith values, as the others have already suggested.Then, instead of performing a brute-force iterative search through the enum values, provide a static
lookup(int)method that performs a binary search through an ordered list/array of all the values.To perform the search, start with the median or middle value as ‘root’, and compare the value we’re looking for with that.
If the value we’re looking for is exactly that, then we’re done. If it’s less than that, then we start searching the lower half of the values, again starting from the middle. If greater, then compare with the value right after it just to see if it falls in range. If it’s still larger, then search in the upper half, and so on.
EDIT: Code sample as requested.
Several notes:
This assumes that the values for
Wealthare already ordered. Otherwise, a quick sort (pun!) should do the trick.This probably isn’t the most efficient implementation, just a quick and dirty one adapted from the pseudo-code on Wikipedia.
If you have fewer than, say, a dozen values, then a linear search might still be more efficient (and the code definitely more self-explanatory) than a binary search. Binary search only really pays off when you have dozens or hundreds of values, and you perform lookups millions of times.
Given your original values, this is evil, premature optimization. I just wanted to bring it up as an option for those who’re working with large sets of values.