C++ vector和set排序效率比较

转自:https://blog.csdn.net/adaptiver/article/details/52925792

1.介绍

vector+sort 实际是快排,快速排序是目前已知的所有排序算法中最快的排序算法。例子:

#include <vector>
#include <set>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
using  namespace  std;
double  time () {
   struct  timeval tv;
   if  (gettimeofday(&tv, NULL) != 0)  return  0.0;
   return  tv.tv_sec + tv.tv_usec / 1000000.0;
}
struct  Score {// 结构体比较简单
   string name;
   double  score;
   bool  operator <( const  Score& right)  const  {
     return  score < right.score;
   }
};
int  main( int  argc,  char ** argv) {
   vector<Score> src;
   for  ( int  i = 0; i < 10000000; i++) {
     int  num =  rand ();
     char  buf[32];
     sprintf (buf,  "%d" , num);
     Score score = { buf, num };
     src.push_back(score);
   }
   {
     double  stime =  time ();
     vector<Score> res;
     for  (vector<Score>::const_iterator it = src.begin();
          it != src.end(); ++it) {
       res.push_back(*it);
     }
     sort(res.begin(), res.end());
     double  etime =  time ();
     printf ( "vector: %f\n" , etime - stime);
   }
   {
     double  stime =  time ();
     multiset<Score> res;
     for  (vector<Score>::const_iterator it = src.begin();
          it != src.end(); ++it) {
       res.insert(*it);
     }
     double  etime =  time ();
     printf ( "multiset: %f\n" , etime - stime);
   }
   return  0;
}

//运行结果:
vector: 11.932973
multiset: 23.243538

把multiset改为set也是类似的结果,sort快排的效率更高。原因:

快速排序速度虽然快,但是在实际的运行过程中,它需要大量地拷贝元素,其拷贝操作的时间复杂度为o(NlogN);

而基于红黑树的multiset在排序的过程中则避免了元素的拷贝。如果元素的内存占用空间比较大,那么multiset排序的速度将比vector+sort快。

原博中把 Score加了个几个string成员数据,set的效率就更高了,//但我试了下不是。可能是和string的具体值有关系,涉及到了拷贝的效率。

2.其他 

  • hash的查找在不碰撞的情况下,效率是最高的,O(1)常数级。
  • 查找其次效率最高的是map,红黑树在插入时就排好序了。vector查找效率是线性的。
  • 百万级的数据放到vector不大合适。因为vector需要连续的内存空间,显然在初始化这个容器的时候会花费很大的容量。 如果内存不是考虑的问题,用vector比map好。map每插入一个数据,都要排序一次。所以速度反不及先安插所有元素,再进行排序。
  • 如果你需要在数据中间进行插入,list 是最好的选择,vector在中间插入效率很低。

 

posted @ 2024-01-14 13:51  lypbendlf  阅读(93)  评论(0编辑  收藏  举报