mardi 7 juin 2022

C++ How can I convert a string to enum to use it in a switch?

I have a list of commands that if a user inputs then it will call separate functions. Talking to a friend he said I should use switch, which is faster and easier to read over "if, else if, else" statements.

When checking how to implement this I realised that I wouldn't be able to because the input is a string and for a switch to work I would need to cast it to an enum and it seems like the most straightforward option I have is to map each of the options like below.

header

    enum class input 
    {
        min,
        max,
        avg,
        count,
        stdev,
        sum,
        var,
        pow
    };

    map<string, input> inMap
    { 
            { "min", input::min },
            { "max", input::max }, 
            { "avg", input::avg },
            { "count", input::count },
            { "stdev", input::stdev }, 
            { "sum", input::sum },
            { "var", input::var },
            { "pow", input::pow }
    };

Is there a more accessible option to use enum where I don't have to map each value? This is very time-consuming and I'm not seeing any benefits at the moment.

cpp.


void test::processInput(vector<string> input) {

        switch (inMap[input[0]]) {

            case inMap::min:
                MIN(input);
                break;

            case inMap::max:
                MAX(input);
                break;

            case inMap::avg:
                AVG(input);
                break;

            case inMap::count:
                COUNT(input);
                break;

            case inMap::stdev:
                STDEV(input);
                break;

            case inMap::sum:
                SUM(input);
                break;

            case inMap::var:
                VAR(input);
                break;

            case inMap::pow:
                POW(input);
                break;

            default:
                std::cout << "Error, input not found" << std::endl;
}

I read some posts about hashing the value instead, is this a good option? At this point wouldn't be just better to continue using if, else if, else?

Thanks!

Aucun commentaire:

Enregistrer un commentaire