结论
C++11新增的emplace() 和 emplace_hint()都比insert效率高
原因
使用 insert() 向 map 容器中插入键值对的过程是,先创建该键值对,然后再将该键值对复制或者移动到 map 容器中的指定位置;
使用 emplace() 或 emplace_hint() 插入键值对的过程是,直接在 map 容器中的指定位置构造该键值对。
上代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33#include <iostream> #include <map> //map #include <string> //string using namespace std; class testDemo { public: testDemo(int num) :num(num) { std::cout << "调用构造函数" << endl; } testDemo(const testDemo& other) :num(other.num) { std::cout << "调用拷贝构造函数" << endl; } testDemo(testDemo&& other) :num(other.num) { std::cout << "调用移动构造函数" << endl; } private: int num; }; int main() { //创建空 map 容器 std::map<std::string, testDemo>mymap; cout << "insert():" << endl; mymap.insert({ "http://c.biancheng.net/stl/", testDemo(1) }); cout << "emplace():" << endl; mymap.emplace( "http://c.biancheng.net/stl/:", 1); cout << "emplace_hint():" << endl; mymap.emplace_hint(mymap.begin(), "http://c.biancheng.net/stl/", 1); return 0; }
程序输出结果为:
复制代码
1
2
3
4
5
6
7
8
9insert(): 调用构造函数 调用移动构造函数 调用移动构造函数 emplace(): 调用构造函数 emplace_hint(): 调用构造函数
在使用 insert() 方法向 map 容器插入键值对时,整个插入过程调用了 1 次 tempDemo 类的构造函数,同时还调用了 2
次移动构造函数。实际上,程序第 28 行代码底层的执行过程,可以分解为以下 3 步:
复制代码
1
2
3
4
5
6
7//构造类对象 testDemo val = testDemo(1); //调用 1 次构造函数 //构造键值对 auto pai = make_pair("http://c.biancheng.net/stl/", val); //调用 1 次移动构造函数 //完成插入操作 mymap.insert(pai); //调用 1 次移动构造函数
而完成同样的插入操作,emplace() 和 emplace_hint() 方法都只调用了 1 次构造函数,这足以证明,这 2 个方法是在
map 容器内部直接构造的键值对。
因此,在实现向 map 容器中插入键值对时,应优先考虑使用 emplace() 或者 emplace_hint()。
最后
以上就是纯真黄蜂最近收集整理的关于STL之map容器的三种插入方式insert emplace emplace_hint那种效率更高结论原因的全部内容,更多相关STL之map容器的三种插入方式insert内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复