Why the switch statement cannot be applied on strings?

前端 未结 20 2847
离开以前
离开以前 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条回答
  •  Happy的楠姐
    2020-11-22 04:28

    As mentioned previously, compilers like to build lookup tables that optimize switch statements to near O(1) timing whenever possible. Combine this with the fact that the C++ Language doesn't have a string type - std::string is part of the Standard Library which is not part of the Language per se.

    I will offer an alternative that you might want to consider, I've used it in the past to good effect. Instead of switching over the string itself, switch over the result of a hash function that uses the string as input. Your code will be almost as clear as switching over the string if you are using a predetermined set of strings:

    enum string_code {
        eFred,
        eBarney,
        eWilma,
        eBetty,
        ...
    };
    
    string_code hashit (std::string const& inString) {
        if (inString == "Fred") return eFred;
        if (inString == "Barney") return eBarney;
        ...
    }
    
    void foo() {
        switch (hashit(stringValue)) {
        case eFred:
            ...
        case eBarney:
            ...
        }
    }
    

    There are a bunch of obvious optimizations that pretty much follow what the C compiler would do with a switch statement... funny how that happens.

提交回复
热议问题