众所周知,map 是 stl 的一个常见容器,它通过 的对应,为我们提供一对一的快速数据处理能力。通过 map,我们可以实现根据 值快速查找对应的结果,查找的复杂度为 ,并且在 值范围很大时对空间的消耗也有限,非常好用。
但是在实际使用 map 的过程中,我们通常忽视了 map 的赋值、清空的方式对性能的消耗,导致花了很多无效的时间。这篇文章重点对 map 赋值和 map 清空的几种方式的耗时做一个对比,便于大家后续在 map 的使用中可以选择正确的方式,提高效率。
map 赋值的选择方式:
方式一: 等于直接赋值
map<int,map<int,int> >m,m2;
//m初始化
for(int i=1;i<10000;i++)
{
map<int,int> t;
for(int j=1;j<100;j++)
{
int a=rand()%1000000;
t[a]++;
}
int b=rand()%1000000;
m[b]=t;
}
//通过=号,直接将m赋值给m2
m2=m;方式二: swap 赋值
map<int,map<int,int> >m,m2;
//m初始化
for(int i=1;i<10000;i++)
{
map<int,int> t;
for(int j=1;j<100;j++)
{
int a=rand()%1000000;
t[a]++;
}
int b=rand()%1000000;
m[b]=t;
}
//通过swap,直接将m赋值给m2
m2.swap(m);方式三: insert 赋值
map<int,map<int,int> >m,m2;
//m初始化
for(int i=1;i<10000;i++)
{
map<int,int> t;
for(int j=1;j<100;j++)
{
int a=rand()%1000000;
t[a]++;
}
int b=rand()%1000000;
m[b]=t;
}
//通过swap,直接将m赋值给m2
m2.insert(m.begin(),m.end());上述三种方式都可以实现赋值的效果,通常如果我们不了解这三种实现方式的差异,随意使用,在数据量很大时会很容易遇到超时而找不到问题在哪里。基于此,我们写了如下测试程序,来统计三种方式耗时的差别。 我们采用windows库函数GetTickCount来统计对应代码时间的消耗,参考代码如下:
#include <windows.h>
DWORD start_time = GetTickCount();
……运行代码
DWORD end_time= GetTickCount();
DWORD duration = end_time - start_time;经过实际测试,这三种方式中,=赋值方式效率最差,swap和insert方式的耗时基本为0. https://cdn.luogu.com.cn/upload/image_hosting/xbv09mef.png
综上所述,建议后续使用map,如果有赋值需要,尽量用swap方式或者insert方式赋值,避免使用=号方式赋值,尤其在数据量大的时候。
整个代码如下:
#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
map<int,map<int,int> >m,m2;
int main()
{
for(int i=1;i<10000;i++)
{
map<int,int> t;
for(int j=1;j<100;j++)
{
int a=rand()%1000000;
t[a]++;
}
int b=rand()%1000000;
m[b]=t;
}
DWORD start_time = GetTickCount();
m2=m;
DWORD end_time= GetTickCount();
DWORD duration = end_time - start_time;
printf("=赋值耗时统计 %u\n",duration);
m2.clear();
start_time = GetTickCount();
m2.swap(m);
end_time = GetTickCount();
duration = end_time-start_time ;
printf("swap耗时统计 %u\n",duration);
m2.clear();
start_time = GetTickCount();
m2.insert(m.begin(),m.end());
end_time = GetTickCount();
duration = end_time-start_time ;
printf("insert耗时统计 %u\n",duration);
return 0;
}