Search code examples
c++dictionaryinitialization-list

Initialize complex map in constructor with initializer list


I was wondering the other day whether it is possible in C++ (any standard) to initialize a map in an initializer list of a constructor with a loop or a more complex procedure than literals such that I can make it a const member variable?

class MyClass {
public:
    const int myInt;
    const std::unordered_map<int, int> map;
    MyClass(int i) : myInt(i), /* initialize map like: for(int i = 0; i < myInt; ++i) { map[i] = whatever; } { }
}

Solution

  • You could use a lambda function inside constructor initializer list. Like so:

    class MyClass {
    public:
        const int myInt;
        const std::unordered_map<int, int> umap;
        MyClass(int i) : myInt(i), umap( [i]() -> decltype(umap) {
          std::unordered_map<int, int> tu;
          for(int j=0; j<i; j++)
            tu[j]=j;
          return tu; 
        }()) {}
    };