栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

unordered

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

unordered

文章目录
    • 测试代码
    • 比较
      • N=1000
      • N=10000
      • N=100000
      • N=1000000
      • N=10000000
      • N=100000000
    • 小结

测试代码

下面这段代码可以比较unordered_set和set增删查的性能

以下数据都是在VS2022 release版本下测的

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define N 10000000
void test()
{
	srand(time(0));
	vectorv;
	v.reserve(N);
	for (int i = 0; i < N; i++)
	{
		v.push_back(rand());
	}

	sets;
	unordered_setus;
//------------------------------------------
	//set insert time
	clock_t begin1 = clock();
	for (int i = 0; i < N; i++)
	{
		s.insert(v[i]);
	}
	clock_t end1 = clock();

	//unorde_set insert time
	clock_t begin2 = clock();
	for (int i = 0; i < N; i++)
	{
		us.insert(v[i]);
	}
	clock_t end2 = clock();
	cout << "set insert: " << end1 - begin1 << endl;
	cout << "unordered_set insert: " << end2 - begin2 << endl << endl;
//------------------------------------------
	//set find time
	clock_t begin3 = clock();
	for (auto e : v)
	{
		s.find(e);
	}
	clock_t end3 = clock();

	clock_t begin4 = clock();
	for (auto e : v)
	{
		us.find(e);
	}
	clock_t end4 = clock();
	cout << "set find: " << end3 - begin3 << endl;
	cout << "unordered_set find: " << end4 - begin4 << endl << endl;
//------------------------------------------

	//set erase time
	clock_t begin5 = clock();
	for (auto e : v)
	{
		s.erase(e);
	}
	clock_t end5 = clock();

	//unordered_set erase time
	clock_t begin6 = clock();
	for (auto e : v)
	{
		us.erase(e);
	}
	clock_t end6 = clock();

	cout << "set earse: " << end5- begin5 << endl;
	cout << "unordered_set erase: " << end6 - begin6 << endl << endl;
}

int main()
{
	test();

	return 0;
}
比较 N=1000

N=10000

N=100000

N=1000000

N=10000000

N=100000000

小结

可以看到unordered_set在增删查方面的性能都比set好,但是为什么我们不用unordered_set去代替set呢?因为set还有一个特点就是有序!而在底层方面,unordered_set底层是哈希,set是红黑树。

处理无序数据时建议用unordered_set,如果需要有序那就选set

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913196.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号