网上大把的map把结构体作为key的博客,但是对于结构体作为值,说明的就很少了。
一个测试用例来说明insert和用等号赋值的区别。

#include <iostream>
#include <string>
#include <map>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

struct Node{
    int a;
    Node(){ a=-9; cout << "Construct null " << a << endl;}
    Node(int tmp){ a=tmp; cout << "Construct " << a << endl; }
    ~Node(){ cout << "Destruct " << a << endl; }
    Node(const Node& node){ a = node.a; cout << "Copy node " << a << endl;}
    Node& operator =(const Node& node){ a = node.a; cout << "= node " << a << endl; return *this;}
};

int main()
{
    std::map<int,Node> ff;
    cout << "**********************" << endl;
    Node m = Node(1);
    cout << "**********************" << endl;
    Node n = Node(2);
    cout << "**********************" << endl;
    Node l = Node(3);
    cout << "**********************" << endl;
    std::pair<int,Node> o(2,n);
    cout << "**********************" << endl;
    ff.insert( o );
    cout << "**********************" << endl;
    ff[1] = m;
    cout << "**********************" << endl;
    ff.insert(std::make_pair(3,l));
    cout << "**********************" << endl;
    ff[4] = Node(4);
    cout << "**********************" << endl;
    ff.erase(1);
    cout << "**********************" << endl;
    ff.erase(2);
    cout << "**********************" << endl;
    ff.erase(3);
    cout << "**********************" << endl;
    ff.erase(4);
    cout << "**********************" << endl;
    return 0;
}

结果如下:

**********************
Construct 1
**********************
Construct 2
**********************
Construct 3
**********************
Copy node 2
**********************
Copy node 2
Copy node 2
Destruct 2
**********************
Construct null -9
Copy node -9
Copy node -9
Destruct -9
Destruct -9
= node 1
**********************
Copy node 3
Copy node 3
Copy node 3
Copy node 3
Destruct 3
Destruct 3
Destruct 3
**********************
Construct 4
Construct null -9
Copy node -9
Copy node -9
Destruct -9
Destruct -9
= node 4
Destruct 4
**********************
= node 3
**********************
Destruct 1
**********************
Destruct 2
**********************
Destruct 3
**********************
Destruct 3
**********************
Destruct 2
Destruct 3
Destruct 2
Destruct 1

总结:
从上面可以看出
ff.insert(std::make_pair(3,l));调用的是拷贝构造函数;
ff[4] = Node(4);
如果该key不存在,会先调用无参数的构造函数,会调用拷贝构造函数,再调用"="运算符拷贝对象;
如果该key存在,会直接调用"="运算符拷贝对象;

因此,当需要将结构体作为值插入map时,需要实现结构体的如上几个构造函数和"="运算符重载。

posted on 2021-06-03 13:56  步孤天  阅读(494)  评论(0编辑  收藏  举报