Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map<string,int> to use strings in switch-case statements

Tags:

c++

Since we can't use strings in switch-case statements directly, as they can't evaluate to constants, I mapped my entries in a map<string,int>.

map<string,int> hash;
    hash["+x"] = 0;
    hash["-x"] = 1;
    hash["+y"] = 2;
    hash["-y"] = 3;
    hash["+z"] = 4;
    hash["-z"] = 5;

Now, I am using them in the switch-case expression :

cin >> bend //assume user entered +x
switch(hash[bend])
            {
                case hash["+y"] :
                    switch(pointedto)
                    {
                        case hash["+x"]: pointedto = hash["+y"];
                            break;
                        case hash["-x"]: pointedto = hash["-y"];
                            break;
                        case hash["+y"]: pointedto = hash["-x"];
                            break;
                        case hash["-y"]: pointedto = hash["+x"];
                            break;
                        case hash["+z"]: pointedto = hash["+z"];
                            break;
                        case hash["-z"]: pointedto = hash["-z"];
                            break;                  
                    }
            }

I am getting errors : an array reference cannot appear in a constant-expression for all the cases. I was expecting hash["+x"] and others, to return int which will result in a constant.

PS : the other alternative is constexpr from C++11 but I was curious to use this one.

like image 506
Naveen Avatar asked Apr 18 '26 18:04

Naveen


1 Answers

Don't fight the language.

The case labels in a C++ switch statement need to be compile time evaluable constant expressions, and a C++ standard library std::map or std::unordered_map doesn't currently provide that.

Use an if else block instead. It might even wind up faster - particularly if you pick an optimal order.

switching on a character array (e.g. '+x'; note the single quotation characters) is often mooted as an alternative for 4 characters or less, but even that is not portable.

like image 106
Bathsheba Avatar answered Apr 21 '26 09:04

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!