编译下面的代码会得到错误消息:type illegal。

int main()
{
    // Compilation error - switch expression of type illegal
    switch(std::string("raj"))
    {
    case"sda":
    }
}

你不能在switch或case中使用字符串。为什么?是否有任何解决方案可以很好地支持类似于打开字符串的逻辑?


当前回答

使用尽可能简单的容器添加一个变体(不需要一个有序的映射)…我不会使用枚举——只是把容器定义放在切换之前,这样就很容易看出哪个数字代表哪个情况。

这将在unordered_map中进行哈希查找,并使用相关的int来驱动switch语句。应该很快。注意,这里使用的是at而不是[],因为我已经将该容器设置为const。使用[]可能是危险的——如果字符串不在映射中,您将创建一个新的映射,并可能以未定义的结果或不断增长的映射结束。

注意,如果字符串不在映射中,at()函数将抛出异常。因此,您可能希望首先使用count()进行测试。

const static std::unordered_map<std::string,int> 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;


}

测试未定义字符串的版本如下:

const static std::unordered_map<std::string,int> 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

}

其他回答

hare对Nick解决方案的评论真的很酷。这里是完整的代码示例(c++ 11):

constexpr uint32_t hash(const std::string& s) noexcept
{
    uint32_t hash = 5381;
    for (const auto& c : s)
        hash = ((hash << 5) + hash) + (unsigned char)c;
    return hash;
}

constexpr inline uint32_t operator"" _(char const* p, size_t) { return hash(p); }

std::string s = "raj";
switch (hash(s)) {
case "sda"_:
    // do_something();
    break;
default:
    break;
}

你不能在开关情况下使用字符串。只允许int和char类型。相反,您可以尝试用enum表示字符串,并在switch case块中使用它

enum MyString(raj,taj,aaj);

在switch case语句中使用它。

    cout << "\nEnter word to select your choice\n"; 
    cout << "ex to exit program (0)\n";     
    cout << "m     to set month(1)\n";
    cout << "y     to set year(2)\n";
    cout << "rm     to return the month(4)\n";
    cout << "ry     to return year(5)\n";
    cout << "pc     to print the calendar for a month(6)\n";
    cout << "fdc      to print the first day of the month(1)\n";
    cin >> c;
    cout << endl;
    a = c.compare("ex") ?c.compare("m") ?c.compare("y") ? c.compare("rm")?c.compare("ry") ? c.compare("pc") ? c.compare("fdc") ? 7 : 6 :  5  : 4 : 3 : 2 : 1 : 0;
    switch (a)
    {
        case 0:
            return 1;

        case 1:                   ///m
        {
            cout << "enter month\n";
            cin >> c;
            cout << endl;
            myCalendar.setMonth(c);
            break;
        }
        case 2:
            cout << "Enter year(yyyy)\n";
            cin >> y;
            cout << endl;
            myCalendar.setYear(y);
            break;
        case 3:
             myCalendar.getMonth();
            break;
        case 4:
            myCalendar.getYear();
        case 5:
            cout << "Enter month and year\n";
            cin >> c >> y;
            cout << endl;
            myCalendar.almanaq(c,y);
            break;
        case 6:
            break;

    }

你可以使用开关字符串。 你需要的是字符串表,检查每一个字符串

char** strings[4] = {"Banana", "Watermelon", "Apple", "Orange"};

unsigned get_case_string(char* str, char** _strings, unsigned n)
{
    while(n)
    {
        n--
        if(strcmp(str, _strings[n]) == 0) return n;
    }
    return 0;
}

unsigned index = get_case_string("Banana", strings, 4);

switch(index)
{
    case 1: break;/*Found string `Banana`*/
    default: /*No string*/
}

使用尽可能简单的容器添加一个变体(不需要一个有序的映射)…我不会使用枚举——只是把容器定义放在切换之前,这样就很容易看出哪个数字代表哪个情况。

这将在unordered_map中进行哈希查找,并使用相关的int来驱动switch语句。应该很快。注意,这里使用的是at而不是[],因为我已经将该容器设置为const。使用[]可能是危险的——如果字符串不在映射中,您将创建一个新的映射,并可能以未定义的结果或不断增长的映射结束。

注意,如果字符串不在映射中,at()函数将抛出异常。因此,您可能希望首先使用count()进行测试。

const static std::unordered_map<std::string,int> 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;


}

测试未定义字符串的版本如下:

const static std::unordered_map<std::string,int> 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

}