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

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

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

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

举个例子:

#include 
#include 

int main(void)
{

    int n;
    while(std::cin >> n)
    {
        std::multimap<int,int> mmpw;

        int high,weigh;
        for(int i=0; istd::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 
#include 
#include 

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

        int id,high,weigh;
        for(int i=0; istd::cin >> id >> pa.second>> pa.first;
            vec.push_back(pa);
        }
        sort(vec.begin(),vec.end(),cmp);
        std::cout << std::endl;
            for(std::vector::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;
}

你可能感兴趣的:(C/C++,stl,map排序,multimap排序,set排序,vector排序)