简体   繁体   中英

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; } { }
}

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; 
    }()) {}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM