C++ STL之set和muliset

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. 易错难点

猜你喜欢

转载自blog.csdn.net/qq_29187197/article/details/82860882
今日推荐