前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++类对象排序operator重载操作

C++类对象排序operator重载操作

作者头像
Michael阿明
发布2020-07-13 16:00:28
5520
发布2020-07-13 16:00:28
举报
  • 类内默认含有this指针,bool operator==(const T& a)
  • 类外则需要写两个参数,bool operator==(const T& a, const T& b)
代码语言:javascript
复制
class People
{
public:
    string name;
    int id;
    People(string n, int i):name(n),id(i){}
    
    bool operator==(const People& a)
    {
        return id == a.id && name==a.name;
    }
    
    bool operator<( const People& a)
    {
        if(id == a.id)
            return name < a.name;
        return id < a.id;
    }
} ;

bool operator==(const People& a, const People& b)
{
    return a.id == b.id && a.name==b.name;
}

bool operator<(const People &a, const People& b)
{
    if(a.id == b.id)
        return a.name < b.name;
    return a.id < b.id;
}

int main()
{
    vector<People> vec;
    vec.push_back(People("Michael",23));
    vec.push_back(People("James",23));
    vec.push_back(People("Kobe",24));
    vec.push_back(People("James",23));

	cout << "-----按id, then name排序----" << endl;
    sort(vec.begin(), vec.end()); // 调用operator<
    for(auto& v : vec)
        cout << v.id << " " << v.name << endl;
    cout << "------去重------------------" << endl;
    vec.erase(unique(vec.begin(), vec.end()),vec.end());
    // unique删除相邻的一样的,要先排序,unique调用 operator==
    for(auto& v : vec)
        cout << v.id << " " << v.name << endl;
    cout << "-----按名称排序-------------" << endl;
    sort(vec.begin(), vec.end(),[](People& a, People& b)
    {
        return a.name < b.name;
    });
    for(auto& v : vec)
        cout << v.id << " " << v.name << endl;
    return 0;
}
代码语言:javascript
复制
运行结果:
-----按id, then name排序----
23 James
23 James
23 Michael
24 Kobe
------去重------------------
23 James
23 Michael
24 Kobe
-----按名称排序-------------
23 James
24 Kobe
23 Michael
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-02-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档