需要帮助理解使用C map作为关联数组

我正在经历Josuttis的“使用Map作为关联数组”(从 The C++ Standard Library – A Tutorial and Reference,2nd Edition开始),并在Stack Overflow上遇到了 Using a std::map as an associative array.现在我对插入地图时调用的构造函数有了更多的疑问.

这是我的示例程序(不使用最佳编码实践;请原谅我):

class C
{
public:

   string s;

   C() { cout << "default " << endl;}

   C(const string& p) : s(p)
   { cout << "one param" << endl;}

   C(const C& obj)
   {
       if (this != &obj)
       {
         s = obj.s;
       }
       cout << "copy constr" << endl;
   }

   C& operator  = (const C& obj)
   {
       if (this != &obj)
       {
             s = obj.s;
       }
      cout << "copy initializer" << endl;
      return *this;
   }
};

int main()
{
    map<int,C> map1;
    C obj("test");

    cout << "Inserting using index" << endl;
    map1[1] = obj;

    cout << "Inserting using insert / pair" << endl;
    map1.insert(make_pair(2,obj));
}

该程序的输出是:

one param
Inserting using index
default
copy constr
copy constr
copy initializer
Inserting using insert / pair
copy constr
copy constr
copy constr
copy constr

我假设按索引初始化地图应调用认构造函数,然后调用赋值运算符.

但是执行map1 [1] = obj会创建以下输出;

Inserting using index
default
copy constr
copy constr
copy initializer

有人能帮助我更好地理解初始化吗?

解决方法

如果您阅读std :: map的规范,则表示operator []相当于(在本例中)
(*((this->insert(make_pair(1,C()))).first)).second

所以这解释了你看到的所有构造函数调用.首先,它调用认构造函数C().然后它调用make_pair,它复制C对象.然后它调用insert,它生成你刚刚创建的pair对象的副本,再次调用C拷贝构造函数.最后,它调用赋值运算符将插入的对象设置为您指定的对象.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...