std::map struct initializer

Run Settings
LanguageC++
Language Version
Run Command
// 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; }
Editor Settings
Theme
Key bindings
Full width
Lines