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在小數據量(可能千以內吧)時,遍歷、查找、添加刪除,都是很快的,完全可以選擇它。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章