2

At this website I found an interesting way to create a switch statement with strings. However, this seems really long and drawn out. I wanted to know if it's possible to turn a particular string into an integer that can be used in a switch statement.

So psuedo code would be something like this

QString str = "spinbox_1";

switch stoi( str )
case 1543:
    //code here
case 2343:
    //code here
case 3424:
    //code here
tisaconundrum
  • 2,156
  • 2
  • 22
  • 37

4 Answers4

2

As @Slava mentioned it is not easily possible. The solution provided by author in mentioned link is probably the most practtical solution. But if you for some reason really need to do it other way and convert string into decimal number, you can use hashing metod. Please refer to below cityhash which is widely used (obviously you can use any other hashing function). https://github.com/google/cityhash

This may be duplicate of: How can I hash a string to an int using c++?

Community
  • 1
  • 1
nosbor
  • 2,826
  • 3
  • 39
  • 63
2

Try to look at this solution: https://github.com/Efrit/str_switch/blob/master/str_switch.h

Unfortunately the description of this solution is avaliable only in Russian (at least I can't find one in English). It is based on computing hash of the string in compile-time. The only limitation it has is it supports strings with 9 character maximum length.

Bearded Beaver
  • 646
  • 4
  • 21
1

If I ever find myself in a similar situation, I use a map to define a specific int from the given string.

For Example:

// The string you want to convert to an int
std::string myString = "stringTwo";

// The mapping that you set for string to int conversions
std::map<std::string, int> stringToInt = \
    {{"stringOne"  , 1},
     {"stringTwo"  , 2},
     {"stringThree", 3}};

// Here, myInt is define as 2
int myInt = stringToInt[myString];

Now you could put myInt into a switch case.

shanek21
  • 67
  • 6
0

No, it is not possible to map a string to an integer uniquely in general - there are simply more strings than integers. You may calculate hash which unlikely to collide for 2 different string and then compare them, but it is still possibility that 2 different strings have the same hash, so you have to compare that strings after you check their hashes. This is how std::unordered_set or std::unordered_map are implemented (aka hash_set and hash_map) so you can use them. But you would not use switch() statement.

Slava
  • 43,454
  • 1
  • 47
  • 90
  • 1
    The OP's intention to use `swich` with `case`es implies that set of possible strings is known at compile time and finite. For any such set it is possible to construct a function that will map strings from that set to integer uniquely – mvidelgauz Jul 12 '16 at 18:13
  • No it does not imply, if there is such function then just use `switch` on it's result – Slava Jul 12 '16 at 18:14