STL vector+sort排序和multiset/multimap排序比较

由 www.169it.com 搜集整理

 在C++的STL库中,要实现排序可以通过将所有元素保存到vector中,然后通过sort算法来排序,也可以通过multimap实现在插入元素的时候进行排序。在通过vector+sort进行排序时,所有元素需要先存入vector容器中,sort在排序时又需要将元素全部取出来再进行排序。multimap底层实现为红黑树,因此元素在插入的过程中就实现了排序。那么到底哪一种排序速度更快呢?

   下面有一个测试程序:

   

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

#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;

}

程序运行结果为:

1

2

3

         time

vector   4.776060

multiset 10.761023

在这个测试中,vector+sort排序比multiset(multimap实现基于multiset)快多了。快速排序是目前已知的所有排序算法中最快的排序算法,因此它比基于堆排序的multiset快。

 在这个测试结果出来之前,大多数人都会毫无疑问地认为multiset排序要更快。这也是有原因的,快速排序速度虽然快,但是在实际的运行过程中,它需要大量地拷贝元素,其拷贝操作的时间复杂度为o(NlogN),而基于红黑树的multiset在排序的过程中则避免了元素的拷贝。如果元素的内存占用空间比较大,那么multiset排序的速度将比vector+sort快。为了测试这个结果,将上面测试程序中的结构体改为:

1

2

3

4

5

6

7

8

9

10

struct Score {

  string name1;

  string name2;

  string name3;

  string name4;

  double score;

  bool operator <(const Score& right) const {

    return score < right.score;

  }

};

然后重新编译运行测试程序,测试结果为:

1

2

3

         time

vector   12.955739

multiset 11.368364

这个测试结果和我们的预期一致。

  总之,我们在使用STL的排序算法时,需要根据不同的元素构造来进行合适的选择,如果都是比较简单的元素,那么适合选择vector+sort来进行排序,对于由字符串构成的占用了比较大的空间的复杂元素,应该使用multiset。如果排序的元素的总个数比较少,那么选择任意一种都可以。

 

转载于:https://www.cnblogs.com/besty/p/4074612.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值