+ 1
Is it possible to use string in switch case?
i want the user to enter the right string with some choices and i thought using if else statement is kinda ineficient so i tried using switch case but i only got an error, is there a way for me to use string in switch case statement
2 ответов
+ 5
No, std::string cannot be used with switch case.
https://stackoverflow.com/questions/650162/why-the-switch-statement-cannot-be-applied-on-strings
Probably the simplest solution is to use a map to map the string to a enum variant which can be used in the case statements, as demonstrated in this answer
https://stackoverflow.com/a/27391233
However, you can also make a hash function that hashes a string into an integer. Marking the hash function constexpr will make the compiler compute the results at compile time, thus reducing the runtime overhead of hashing. It is demonstrated here, although even I don't understand what is happening in the hash function
https://stackoverflow.com/a/46711735
+ 3
Get faster results
https://www.google.com/search?q=use+string+in+switch+case+c%2b%2b