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

本文详细介绍了C++ STL中的set与multimap容器的特点与应用,对比了两者存储方式的不同,通过实例展示了如何使用multimap进行排序,并提供了一种使用vector结合自定义比较函数实现更复杂排序需求的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值