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

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

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


当前回答

开关仅适用于整型(int, char, bool等)。为什么不使用映射将字符串与数字配对,然后将该数字与开关使用呢?

其他回答

C++

Constexpr哈希函数:

constexpr unsigned int hash(const char *s, int off = 0) {                        
    return !s[off] ? 5381 : (hash(s, off+1)*33) ^ s[off];                           
}                                                                                

switch( hash(str) ){
case hash("one") : // do something
case hash("two") : // do something
}

更新:

上面的例子是c++ 11。这里的constexpr函数必须是单语句。这在接下来的c++版本中得到了放宽。

在c++ 14和c++ 17中,你可以使用以下哈希函数:

constexpr uint32_t hash(const char* data, size_t const size) noexcept{
    uint32_t hash = 5381;

    for(const char *c = data; c < data + size; ++c)
        hash = ((hash << 5) + hash) + (unsigned char) *c;

    return hash;
}

c++ 17也有std::string_view,所以你可以用它来代替const char *。

在c++ 20中,您可以尝试使用consteval。

在c++中,字符串不是一等公民。字符串操作是通过标准库完成的。我想,这就是原因。另外,c++使用分支表优化来优化开关case语句。看看这个链接。

http://en.wikipedia.org/wiki/Switch_statement

std::map + c++ 11没有枚举的lambdas模式

潜在的平摊O(1)的unordered_map:在c++中使用HashMap的最佳方式是什么?

#include <functional>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

int main() {
    int result;
    const std::unordered_map<std::string,std::function<void()>> m{
        {"one",   [&](){ result = 1; }},
        {"two",   [&](){ result = 2; }},
        {"three", [&](){ result = 3; }},
    };
    const auto end = m.end();
    std::vector<std::string> strings{"one", "two", "three", "foobar"};
    for (const auto& s : strings) {
        auto it = m.find(s);
        if (it != end) {
            it->second();
        } else {
            result = -1;
        }
        std::cout << s << " " << result << std::endl;
    }
}

输出:

one 1
two 2
three 3
foobar -1

在静态方法中使用

要在类中有效地使用这种模式,可以静态地初始化lambda映射,否则每次从头构建时都要付出O(n)。

在这里,我们可以摆脱静态方法变量的{}初始化:类方法中的静态变量,但我们也可以使用在:c++中的静态构造函数?我需要初始化私有静态对象

必须将lambda上下文捕获[&]转换为参数,否则将未定义:const static auto lambda与capture by reference一起使用

示例,产生与上面相同的输出:

#include <functional>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>

class RangeSwitch {
public:
    void method(std::string key, int &result) {
        static const std::unordered_map<std::string,std::function<void(int&)>> m{
            {"one",   [](int& result){ result = 1; }},
            {"two",   [](int& result){ result = 2; }},
            {"three", [](int& result){ result = 3; }},
        };
        static const auto end = m.end();
        auto it = m.find(key);
        if (it != end) {
            it->second(result);
        } else {
            result = -1;
        }
    }
};

int main() {
    RangeSwitch rangeSwitch;
    int result;
    std::vector<std::string> strings{"one", "two", "three", "foobar"};
    for (const auto& s : strings) {
        rangeSwitch.method(s, result);
        std::cout << s << " " << result << std::endl;
    }
}

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

这将在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

}

开关仅适用于整型(int, char, bool等)。为什么不使用映射将字符串与数字配对,然后将该数字与开关使用呢?