4 ms·
Yeah, it creates a jump table, so basically an O(1) operation in assembly rather than O(n) comparison worst case for every case. However, this means switch _on
by stabbles 7y ago
Yeah, it creates a jump table, so basically an O(1) operation in assembly rather than O(n) comparison worst case for every case.
However, this means switch _only_ works with integers, which is rather limited and confuses newcomers. For instance this does not compile:
void f(std::string const &str) {
switch(str) {
case "option_1":
std::cout << "First option\n";
break;
case "option_2":
std::cout << "Second option\n";
break;
default:
std::cout << "None of the above\n";
}
}
- beached_whale 7y agoThe workaround is constexpr hashing void f(std::string const &str) { switch(hash(str)) { case hash("option_1"): std::cout << "First option\n"; break; case hash("option_2"): std::cout << "Second option\n"; break; default: std::cout << "None of the above\n"; } } It could be as little as converting the final 8 bytes to a uint64_t above and using that. That just happens to be all of them in this case, but there are a bunch of them. Or using minimal perfect hashing. None of this is the language though
- rowanG077 7y agoCan you guaranty at compile time that any hash you switch on is unique? Else this is just really dangerous if you don't have perfect hashing for the object you switch on.