前面我们简单提到过emplace_hint()这个插入函数,在能够巧用迭代器的情况下就能实现map高效插入元素。emplace_hint(hint,key,val)有3各参数,第一个是位置迭代器hint,第二个是key键值,第三个是val值。它的返回值为:如果成功插入返回插入元素对应的迭代器,否则返回hint。

如何巧用迭代器?大多数情况下emplace_hint()都是进行批量元素插入。比如我要插入1000000个{int,int}元素,我使用emplace_hint()最为高效:

#include<bits/stdc++.h>//万能头
#include<string>
#include<map>//包含头文件,养成好习惯 
/*emplace_hint()*/
using namespace std;
void test()
{
map<int,int> mp;
auto hint = mp.begin();
for(int i=0;i<1000000;++i)hint=mp.emplace_hint(hint,i,i+1);
}
int main(){
    test();
    return 0;
}

结果为:Process exited after 0.4297 seconds with return value 0

对比'[]',已经能够看到差距了:

#include<bits/stdc++.h>//万能头
#include<string>
#include<map>//包含头文件,养成好习惯 
/*'[]'*/
using namespace std;
void test()
{
map<int,int> mp;
auto hint = mp.begin();
for(int i=0;i<1000000;++i)mp[i]=i+1;
}
int main(){
    test();
    return 0;
}

结果为:Process exited after 1.171 seconds with return value 0

对比insert(),也还行:

#include<bits/stdc++.h>//万能头
#include<string>
#include<map>//包含头文件,养成好习惯 
/*insert()*/
using namespace std;
void test()
{
map<int,int> mp;
auto hint = mp.begin();
for(int i=0;i<1000000;++i)mp.insert({i,i+1});
}
int main(){
    test();
    return 0;
}

结果为:Process exited after 1.073 seconds with return value 0

对比emplace()查不多:


#include<bits/stdc++.h>//万能头
#include<string>
#include<map>//包含头文件,养成好习惯 
/*insert()*/
using namespace std;
void test()
{
map<int,int> mp;
auto hint = mp.begin();
for(int i=0;i<1000000;++i)mp.emplace(i,i+1);
}
int main(){
    test();
    return 0;
}

结果为:Process exited after 1.111 seconds with return value 0

总结:emplace_hint()在插入1000000个{int,int}元素中表现最佳,几乎比其他函数或是'[]'都要快上1倍,所以给map批量添加元素时最好使用emplace_hint()!

点赞(0)

C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:

一点编程也不会写的:零基础C语言学练课程

解决困扰你多年的C语言疑难杂症特性的C语言进阶课程

从零到写出一个爬虫的Python编程课程

只会语法写不出代码?手把手带你写100个编程真题的编程百练课程

信息学奥赛或C++选手的 必学C++课程

蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程

手把手讲解近五年真题的蓝桥杯辅导课程

Dotcpp在线编译      (登录可减少运行等待时间)