c++ - 映射运算符 [] 的编译错误

标签 c++ dictionary

为什么我会收到“recMap[key] = rec;”的编译错误在下面的代码中,但等效的语句工作正常吗?我有其他代码可以执行此操作。我错过了什么简单的事情?

#include <map>

class MyRec {
   public:
   MyRec(int numberIn) : myNumber(numberIn) { };
   int myNumber;
};

int main(int argc, char **argv)
{
   typedef std::map<int, MyRec> Recs;
   Recs recMap;
   int num=104702;
   int key=100923;

   MyRec rec(num);

   recMap[key] = rec; // Doesn't compile
   // error: no matching function for call to MyRec::MyRec()
   // samp.cpp:5: note: candidates are: MyRec::MyRec(int)
   // samp.cpp:3: note:                 MyRec::MyRec(const MyRec&)

   // Why do I receive the compile error for the above if it is the same as:
   (*((recMap.insert(std::make_pair(key,rec))).first)).second;

   recMap.insert(std::pair<int, MyRec>(key,rec)); // Works also of course
}

最佳答案

考虑这个片段:

std::map<int, Foo> map;
map[0];

即使没有为键 0 插入对象,这实际上也可以正常工作。原因是,std::map::at()std 之间存在差异: :map::运算符 []():

std::map::at() 仅返回对 map 内对象的引用。如果给定键不存在对象,则会引发异常。

std::map::operator []() 也返回一个引用,但是如果给定键没有对象,它会在映射并返回对此新创建的对象的引用。为了创建对象 std::map 必须调用默认构造函数(没有附加参数的构造函数)。

这就是您的代码无法编译的原因:您的类 MyRec 不是默认可构造的,但 std::map::operator [] 需要这个。


因此您有三个选择:

  1. 使用std::map::insert()
  2. 使用std::map::emplace()
  3. 使 MyRec 默认可构造。

关于c++ - 映射运算符 [] 的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22561405/

相关文章:

c# - 从字典<>中以文化不变/大小写不变的方式寻找值(value)<>

python - 如何在Python中使用字典作为字典的键

c# - 浮点加法 : loss-of-precision issues

c++ - 使用 openssl 检查 PKCS#7 中的根证书是否被撤销

c++ - boost::interprocess -- std::string 与 std::vector

c++ - 如何使用 std::map 将 bool 映射到 3d 点结构?

python - 获取字典中具有第二个和第三个最大值的键

python - 将字典转换为数据帧的一列,同时将字典行名称保留在另一列中(python)

java - Java 中的列表和 map

c++ - 在 "if"语句中调用 std::set 函数时的意外评估结果