如何在声明时将对象插入 std::map

How to insert object into std::map while declaration

问题:

我试图在编译时将 class 的实例插入到 std::map 中,但总是出现以下错误。

main.cpp:18:12: error: ‘_info’ was not declared in this scope
     _info(1)
        ^

行号 18 指向下面的代码块

15. std::map<std::string, Info > lookup  {
16.      {
17.        "aclk",
18.        _info(1)
19.      }
20.    };

代码:

#include <random>
#include <iostream>
#include <functional>
#include <map>

class Info{
    int _info;
public:
   Info(int info){
     _info = info;
   }   
}; 


 std::map<std::string, Info > lookup  {
  {
    "aclk",
    _info(1)
  }
};

int main()
{
   //dummy
}

观察:

当我动态创建对象时,我没有看到任何此类错误。

const std::map<std::string, Info > lookup  {
  {
    "aclk",
    new Info(1)
  }
};

但是地图 const 和实例插入 new 没有任何意义。

您必须提供 Info 类型的对象而不是其数据成员 _info。例如

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    1
  }
};

这是有效的,因为 class Info 有一个转换构造函数。

或者(例如,如果构造函数是显式的)

 std::map<std::string, Info > lookup  {
  {
    "aclk",
    Info(1)
  }
};