Why the switch statement cannot be applied on strings?

前端 未结 20 2952
离开以前
离开以前 2020-11-22 03:58

Compiling the following code and got the error of type illegal.

int main()
{
    // Compilation error - switch expression of type illegal
    sw         


        
20条回答
  •  星月不相逢
    2020-11-22 04:31

    To add a variation using the simplest container possible (no need for an ordered map)... I wouldn't bother with an enum--just put the container definition immediately before the switch so it'll be easy to see which number represents which case.

    This does a hashed lookup in the unordered_map and uses the associated int to drive the switch statement. Should be quite fast. Note that at is used instead of [], as I've made that container const. Using [] can be dangerous--if the string isn't in the map, you'll create a new mapping and may end up with undefined results or a continuously growing map.

    Note that the at() function will throw an exception if the string isn't in the map. So you may want to test first using count().

    const static std::unordered_map string_to_case{
       {"raj",1},
       {"ben",2}
    };
    switch(string_to_case.at("raj")) {
      case 1: // this is the "raj" case
           break;
      case 2: // this is the "ben" case
           break;
    
    
    }
    

    The version with a test for an undefined string follows:

    const static std::unordered_map string_to_case{
       {"raj",1},
       {"ben",2}
    };
    // in C++20, you can replace .count with .contains
    switch(string_to_case.count("raj") ? string_to_case.at("raj") : 0) {
      case 1: // this is the "raj" case
           break;
      case 2: // this is the "ben" case
           break;
      case 0: //this is for the undefined case
    
    }
    

提交回复
热议问题