STL vector 跟 MFC CArray 效率比较

vector做为连续的内存容器,在对于查找排序有着天然的优势,但是要是频繁的进行删除跟插入,就要用deque或者list比较合适。

当在windows下进行开发,MFC能够极大的缩短编程时间,由于MFC中CArray的使用已经变的很简单。就有必要对vector 跟 CArray 之间做个比较。

 

Note : 仅仅测试500000个字符串进行插入

测试环境  windows控制台

注:默认在windows控制台是不支持使用MFC库。需要在project->setting->General中的Microsoft Foundation Classes:

中下拉选择 Use MFC in a Static Library.来支持使用MFC。

 1 #include <afxtempl.h>
 2 #include <iostream>
 3 #include <time.h>
 4 #include <vector>
 5 
 6 
 7 using namespace std;
 8 
 9 typedef clock_t vTime;
10 
11 class CTimeCls
12 {
13 public:
14 
15     void Start()
16     {
17         m_stime = clock();
18     }
19     void Finish()
20     {
21         m_ftime = clock();
22     }
23 
24     friend ostream& operator << ( ostream& os, const         CTimeCls& time)
25   {
26     return os << "The time for this function use : "\
27       << double( time.m_ftime - time.m_stime ) / CLOCKS_PER_SEC <<" s"<< endl;
28   }
29   CTimeCls(){}
30 
31   ~CTimeCls(){}
32 private:
33   vTime m_stime;
34   vTime m_ftime;
35 };
36 
37  
38 
39 void InsertNumUseVector( vector < int >& v , int nNum)
40 {
41   v.push_back( nNum );
42 }
43 
44 void InsertCStrUseCArray( CArray<CString, CString&>& arr, CString& strText)
45 {
46   arr.Add( strText );
47 }
48 
49 void InsertCStrVector( vector < CString > & vs, const CString& strText )
50 {
51   vs.push_back( strText );
52 }
53 int main(int argc, char* argv[])
54 {
56   CTimeCls timer; 59   vector < CString > vs; 60   CString strText = "hello"; 61 62   timer.Start(); 63   for ( int i = 0 ; i < 500000; ++i ) 64   { 65     InsertCStrVector( vs, strText ); 66   } 67   timer.Finish(); 69   cout << timer; 70 71   timer.Start(); 73   CArray <CString, CString&> arr; 74   for ( i = 0; i < 500000; ++i) 75   { 76     InsertCStrUseCArray( arr, strText ); 77   } 78   timer.Finish(); 80   cout << timer; 81 82   getchar(); 83   return 0; 84 }

 

//////////////////////////

vector : 0.25 s

CArray: 5.485 s

//////////////////////////

以上在VS6.0能编译通过

虽然只是测试插入数据,但是也足以证明 为什么许多说明文档或者网上评论,一般一致认为应该多用vector。

 

posted @ 2012-11-30 18:21  CiMoar  阅读(1867)  评论(1编辑  收藏  举报