C++STL中,map/multimap,set/multiset 和vector的排序

来源:互联网 发布:分期网站源码 编辑:程序博客网 时间:2024/05/22 15:42

set存储已排序的无重复的元素,multiset是元素可以重复.为实现快速的集合运算set内部数据组织采用红黑树(一种严格意义上的平衡二叉树).

map存储key-value对,按key排序,map的内部数据结构也是红黑树,并且key值无重复.multimap允许key值重复.

在排序的时候,默认是按照key值从小到大排序,当key相等时,按pair< key,value>的原始顺序排序,即key相等时候,这些key相等的数的相对顺序没有变,并没有根据value再排序

举个例子:

#include <iostream>#include <map>int main(void){    int n;    while(std::cin >> n)    {        std::multimap<int,int> mmpw;        int high,weigh;        for(int i=0; i<n; ++i)        {            std::cin >> high >> weigh;            mmpw.insert(std::pair<int,int>(weigh,high));        }        std::cout << std::endl;        for(std::multimap<int,int>::iterator it = mmpw.begin(); it!=mmpw.end(); ++it)            std::cout << it->first << " "  << it->second << std::endl;        std::cout << std::endl;    }    return 0;}

输入:
6
80 100
65 100
75 80
60 95
82 101
81 70

输出:
70 81
80 75
95 60
100 80 当key=100时,在原来的顺序中80在65前面,保持不变
100 65
101 82

换个顺序输入:
6
65 100
75 80
80 100
60 95
82 101
81 70

70 81
80 75
95 60
100 65 当key=100是,在原来的顺序中,65在80前,保持不变
100 80
101 82

如果想从大到小排序,

std::multimap<int,int> mmp ;  的地方,改为std::multimap<int,int,std::greater<int>> mmp;

但是同样的,它只是对key排序,在key相等时,并没有再根据value排序。

如果我们想先根据key排序,在key相等时,再对value排序,这时我们可以使用vector。

#include <iostream>#include <vector>#include <algorithm>struct pair{    int first;    int second;};bool cmp(const pair &a, const pair &b) {    if(a.first == b.first)        return a.second > b.second;  //从大到小排序  如果希望从小到大,把>改为<即可    return a.first > b.first;}//可以根据上面两个< > 符号调整规则排序int main(void){    int n;    while(std::cin >> n)    {        std::vector<pair> vec;        int id,high,weigh;        for(int i=0; i<n; ++i)        {            pair pa;            std::cin >> id >> pa.second>> pa.first;            vec.push_back(pa);        }        sort(vec.begin(),vec.end(),cmp);        std::cout << std::endl;            for(std::vector<pair>::iterator it = vec.begin(); \            it!=vec.end(); ++it)                    std::cout << it->first << " "  \                    << it->second << std::endl;        std::cout << std::endl;    }    //std::cout << std::endl;    return 0;}
阅读全文
0 0
原创粉丝点击