Quick actions

cmd+k|ctrl+k

Navigation

Languages

std::map struct initializer

Snippet info

Language

Cpp

Visibility

public

Author

hermann.max

Created

2016-01-21T13:08:28Z

Updated

2016-01-21T13:08:41Z

// Map enum to a describing struct
#include <iostream>
#include <string>
#include <map>

enum { First, Second };

struct Foo { 
    std::string name; 
    Foo(std::string name_):name(name_){} 
    Foo():name("(unknown)"){}
};

// Variant 1: Use array for mapping (requires identical enumeration as in enum)
Foo foo[] = {
    Foo("Hullo"),  // First
    Foo("cudepud") // Second
};

// Variant 2: Use map (allows for arbitrary, non-consecutive enum values)
std::map<int,Foo> bar = {{First,Foo("Hallo")}, {Second,Foo("cadepad")}};

int main()
{
    using namespace std;
    cout << foo[First].name << " " << foo[Second].name << " ("
         << sizeof(foo)/sizeof(foo[0]) << " Foo's in array)" << endl;
    cout << bar[First].name << " " << bar[Second].name << " ("
         << bar.size() << " Foo's in map)" << endl;
    return 0;
}
INFO