C++ STL之set和muliset

本文详细介绍了C++ STL中set和multiset容器的使用方法,包括自定义比较函数和比较类,以及如何插入和遍历元素。通过示例代码展示了如何创建包含学生信息的set,并按ID和年龄排序。

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

1. 定义
二叉树优势自动排序。set不会出现多个相同关键字,multiset可以出项相同的关键字
2. 基本用法

//头文件
#include<iostream>
#include<set>
using namespace std;

struct Students
{
    string id;
    int age,height;
    Students(string s,int a,int h):id(s),age(a),height(h){}
    Students() {}
};

class comp{
public:
    bool operator()(const Students &s1,const Students &s2){
        if(s1.id!=s2.id) return s1.id<s2.id;
        return s1.age<s2.age;
    }
};

int main(){
    set<Students,comp> se;
    se.insert(Students("zhou",12,134));
    se.insert(Students("wu",13,42));
    se.insert(Students("zheng",34,43));
    se.emplace("wang",13,43);
    se.emplace("zhou",23,43);
    for(auto it=se.begin();it!=se.end();it++){
        cout<<it->id<<" "<<it->age<<" "<<it->height<<endl;
    }
    return 0;
}
方法三 自定义比较函数
示例代码如下:
#include<iostream>
#include<set>
using namespace std;

struct Students
{
    string id;
    int age,height;
    Students(string s,int a,int h):id(s),age(a),height(h){}
    Students() {}
};

bool cmp(const Students &s1,const Students &s2){
    if(s1.id!=s2.id) return s1.id<s2.id;
    return s1.age<s2.age;
}

int main(){
    set<Students,decltype(cmp)*> se(cmp);
    se.insert(Students("zhou",12,134));
    se.insert(Students("wu",13,42));
    se.insert(Students("zheng",34,43));
    se.emplace("wang",13,43);
    se.emplace("zhou",23,43);
    for(auto it=se.begin();it!=se.end();it++){
        cout<<it->id<<" "<<it->age<<" "<<it->height<<endl;
    }
    return 0;
}
只要是assignable、copyable、comparable(根据某个排序准则)的型别T,都可以成为set或者multisets的元素。如果没有特别的排序原则,采用默认的less,已operator < 对元素进行比较,以便完成排序。
排序准则必须遵守以下原则:
 必须是“反对称的”,对operator <而言,如果x < y为真,y<x为假。
 必须是“可传递的”,对operator <而言,如果x<y为真,y<z为真,那么x<z也为真。
 必须是“非自反的”,对operator<而言,x<x永远为假。

3. 易错难点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值