C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ set自定义排序

C++之set自定义排序问题

作者:沧海漂游_

这篇文章主要介绍了C++之set自定义排序问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

set简介

set一般插入元素时,默认使用关键字类型的< 运算符来比较两个关键字,

故一般插入后为升序,但是针对自定义数据结构,

如结构体,没有< 运算符,故无法进行比较。

针对自定义数据结构或者说自定义set排序规则有如下几种方法:

方法一 重载<

在自定义结构体中重载< 则可以实现默认排序,

示例代码如下:

#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 operator <(const Students &s) const {
        if(id!=s.id) return id<s.id;
        else return age<s.age;
    }
};
int main(){
    set<Students> 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() {}
};

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

方法三 参考《C++ primer(第五版)》

示例代码如下:

#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;
}

上述代码中,用decltype 来指出自定义操作的类型。

当使用decltype 来获得一个函数指针类型时,必须加上一个* 来指出我们要使用一个给定函数类型的指针。

cmp 来初始化se对象,这表示当我们向se中插入元素时,通过调用cmp来为这些元素排序。

可以使用cmp代替&cmp作为构造函数的参数,因为当我们使用一个函数的名字时,在需要的情况下会自动转化为一个指针,使用&cmp 效果也是一样的。

insert 和 emplace 的使用

emplace对应insert,emplace_back对应于push_back;

但是insertpush_back是直接将对象拷贝至容器当中,而emplaceemplace_back是先调用存储对象构造函数,在内存中生成对象,然后拷贝至容器中。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文