stl容器遍历测试

使用vc2010,对vector,set,map,list,deque,queue的遍历速度进行了下测试,代码如下

#include <windows.h>
#include <stdio.h>

#include <vector>
#include <set>
#include <map>
#include <list>
#include <deque>
#include <queue>


int main(int argn, char*[] argv)
{
std::vector<int> vec;
	std::set<int> set;
	std::map<int, int> mp;
	std::list<int> lt;
	std::deque<int> dqe;
	std::queue<int> que;
	int t = 0;

	for (int i = 0; i < 1000000; ++i)
	{
		vec.push_back(i);
		set.insert(i);
		mp.insert(std::make_pair(i, i));
		lt.push_back(i);
		dqe.push_back(i);
		que.push(i);
	}

	printf("init complete\n\n");

	//
	DWORD s = GetTickCount();
	for (int j = 0; j < 1000; ++j)
	for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++ it)
	{
		t += *it;
	}
	printf("vec: %d\n", GetTickCount() - s);

	//
	s = GetTickCount();
	for (int j = 0; j < 1000; ++j)
	for (std::set<int>::iterator it = set.begin(); it != set.end(); ++ it)
	{
		t += *it;
	}
	printf("set: %d\n", GetTickCount() - s);

	//
	s = GetTickCount();
	for (int j = 0; j < 1000; ++j)
	for (std::map<int, int>::iterator it = mp.begin(); it != mp.end(); ++ it)
	{
		t += it->first;
	}
	printf("map: %d\n", GetTickCount() - s);

	//
	s = GetTickCount();
	for (int j = 0; j < 1000; ++j)
	for (std::list<int>::iterator it = lt.begin(); it != lt.end(); ++ it)
	{
		t += *it;
	}
	printf("list: %d\n", GetTickCount() - s);

	//
	s = GetTickCount();
	for (int j = 0; j < 1000; ++j)
	for (std::deque<int>::iterator it = dqe.begin(); it != dqe.end(); ++ it)
	{
		t += *it;
	}
	printf("deque: %d\n", GetTickCount() - s);

	//
	s = GetTickCount();
	for (int j = 0; j < 1000; ++j)
	while (!que.empty())
	{
		t += que.front();
		que.pop();
	}
	printf("queue: %d\n", GetTickCount() - s);

	//

	return 0;
}

结果:


queue比较特殊,就不说了,代码中把百万级别的整数进行了1000次遍历,在结果中vector的速度是最快的,其次是deque,而map遍历最慢(hash_map的遍历速度应该也是很快的),所以通常情况下:

1.如果需要进行大量的遍历操作和随机读写,vector是最佳的选择

2.如果在需要大量遍历的情况下,且需要进行较多的数据插入操作的话,使用deque较为合适,比较均衡

3.如果进行大量插入删除操作,可选择list

4.如果需要查找等等操作的时候,还是选择map等关系型容器


以上应用场景均是相对而言,实际使用中,vector在小数据量(可能千以内吧)时,遍历、查找、添加删除,都是很快的,完全可以选择它。





  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值