I studied enums which expects only integer inputs and returns corresponding value to it.I want to achieve same thing but I only have strings as a input. I want to make following work -
and probable statment could be -
string sTpes = Types("abs"); //this should return "Absolute"
or
string sTpes = Types("MXD"); //this should return "MIXED"
If not using enums ,please suggest me possible ways to achieve this.
Well, for small number of enums I just use if-else.
But I was being genuinely curious, rather than critical. As I'm between jobs I'm taking the chance to revisit all the decisions I've made so far (in time for my job interviews...)
Note
[1] CompareNoAccents() -- in namespace Utils -- converts all accented chars to their unaccented equivalent and then calls stricmp() or strcasecmp() -- depending on build
[2] I am not guarding against NULL pointers here, as that's done a level up
[3] This code is called by a C-based XML parser, as well as the config GUI, so I am avoiding the use of exceptions here (so I don't mis return codes and exception in the parsing code)
It could be modified to return a string via the out param, but I would use enum values internally and then map the enum back to a string for display purposes.
Enumerated types are types that are enumerated - obviously. Why/how would you enumerate a string? That completely defeats the purpose of enumerated types; therefore convoluting your code entirely. Just create a namespace holding your constants and move on.
But I was being genuinely curious, rather than critical.
What makes you think I thought you were being critical?
andywestken wrote:
Well, for small number of enums I just use if-else.
I see. Even though a map's lookup complexity is O(logn), you prefer a
linear search in this case, as the constant factor is (probably) smaller.
But is it really worth it? Is this function really going to be the speed bottleneck of your app?
If yes, there are ways you can achieve O(logn) time complexity without the map overhead.
Well, this code is not esp. speed critical. So as you say, with a small number of strings to test, the penalty of a linear search will (probably) be minor.
For larger sets of string/id mappings I would trade up to map, and then unorder_map/hash_map. But I wouldn't expect to come across an enum which requires this treatment.
But I would use map::find() to retrieve the id, rather than [], so I could handle not found.
Andy
I didn't assume you were being ciritical; I just decided to make my motivation as clear as possible.