1

I have an enum like this

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

I am trying to get the index value of the enum by passing a string value.

For example, GetenumIndex("Mon") will return 0.

The prototype of the function is like:

week GetenumIndex(string )

What is the idiomatic way in C++ to implement such a conversion function?

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
user8364661
  • 39
  • 1
  • 3

1 Answers1

1

Well, here you go:

#include <iostream>
#include <string>
#include <map>
#include <exception>

enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

week GetenumIndex( const std::string s ) {    
    static std::map<std::string,week> string2week {
       { "Mon", Mon }, 
       { "Tue", Tue },
       { "Wed", Wed }, 
       { "Thur", Thur },
       { "Fri", Fri },
       { "Sat", Sat }, 
       { "Sun", Sun }   
    };
    auto x = string2week.find(s);
    if(x != std::end(string2week)) {
        return x->second;
    }
    throw std::invalid_argument("s");
}

int main() {
    week w = GetenumIndex("Thur");
    std::cout << w << std::endl;
}

See it live here.

user0042
  • 7,917
  • 3
  • 24
  • 39