Whether it is possible to set somehow indexes enum oh at std::vector ?

An example of what I mean:

 enum name_index {t1,t2,t3,t4}; std::vector<type> vec; 

item access:

 vec[t1];//vec[0] vec[t2];//vec[1] vec[t3];//vec[2] vec[t4];//vec[3] 

    2 answers 2

    Yes, essentially enum is a block of constants, so the code below works fine.

     enum t{ A,B,C,D }; int main() { int m[4]; m[A] = 1; m[B] = 2; m[C] = 3; m[D] = 4; for (int i : m) cout <<i; return 0; } 

    http://ideone.com/lIXYLZ

    • 7
      The only thing is to be careful if enum t {a, b, c = 15, d }; is written somewhere enum t {a, b, c = 15, d }; - andy.37

    enum in C ++ is different. If enum is simple, then the conversion is implicit (you have already been shown this), but if the more modern enum class is used, then you need an explicit type conversion.

     #include <iostream> using namespace std; enum class t{ A,B,C,D }; int main() { // your code goes here int m[4]; m[static_cast<int>(t::A)] = 1; m[static_cast<int>(t::B)] = 2; m[static_cast<int>(t::C)] = 3; m[static_cast<int>(t::D)] = 4; for (int i : m) cout <<i; return 0; } 

    ( http://ideone.com/951Lcq )

    • You have to stick up when displaying the number, it is ugly. - gbg
    • one
      If the sole purpose is to use enumeration values ​​as numbers, then the enum class here only adds problems. Enum ordinary enough. - αλεχολυτ
    • @gbg I just rewrote the code from the first answer :) - Harry