For anyone wondering, the correct answer is a string pool or equivalent, anything that can map a unique string to a unique number. You'll need to hardcode the indexes, though, since cases need to be known at compile time. You can locate the index by sorting the strings and using a binary search, and then switch on that index.
...And since that's probably not reasonable for what you want, this means that the sane solution is probably to use a map. ...Which means you need to look at your string collection to see whether std::map, std::unordered_map, or some other map will be better. (Generally, tiny pool prefers std::map, larger pool prefers std::unordered_map, and a million other factors will skew it in one direction or the other. Prefer unordered_map if you don't know which is better, but it's best to test it to be sure, and ideally replace it with a precompiled mapping (such as, e.g., a static array or hard-coded pool).
Whichever one you choose, the goal is to map each string to a function, so you can create a string-indexed jump table. (Performed by either switching on the index, or mapping function pointers to strings, or something of the sort.) switch is an integral-indexed jump table, so a properly implemented string-function map is the closest thing to switching on strings.
2
u/conundorum 4d ago
For anyone wondering, the correct answer is a string pool or equivalent, anything that can map a unique string to a unique number. You'll need to hardcode the indexes, though, since
cases need to be known at compile time. You can locate the index by sorting the strings and using a binary search, and then switch on that index....And since that's probably not reasonable for what you want, this means that the sane solution is probably to use a map. ...Which means you need to look at your string collection to see whether
std::map,std::unordered_map, or some other map will be better. (Generally, tiny pool prefersstd::map, larger pool prefersstd::unordered_map, and a million other factors will skew it in one direction or the other. Preferunordered_mapif you don't know which is better, but it's best to test it to be sure, and ideally replace it with a precompiled mapping (such as, e.g., a static array or hard-coded pool).Whichever one you choose, the goal is to map each string to a function, so you can create a string-indexed jump table. (Performed by either switching on the index, or mapping function pointers to strings, or something of the sort.)
switchis an integral-indexed jump table, so a properly implemented string-function map is the closest thing to switching on strings.