信息学奥赛第十五节 —— SET集合与重载运算符

SET的性质、特点
  • set是一个集合,且集合内的元素有序,除此之外,集合中不允许有重复的元素(multiset中的元素可以重复)。
  • set中的元素不可以直接修改。那么,如果要修改集合中的元素,应该如何操作?答:先删除,再插入新的元素,效果等同于修改了旧的元素
greater比较器与less比较器

set中的元素之所以默认从小到大排序,是因为其默认使用的是less比较器。在编写代码时重载比较器,就可以使set中的元素默认为从大到小排序。需要注意的是,如果将默认的less比较器修改为了greater比较器,在编写打印函数时也需要重载比较器。参考代码如下:

#include <iostream>
#include <set>

using namespace std;

void print1(set<int> s)
{
    set<int>::iterator it;
    for (it = s.begin();it != s.end();it ++) cout << *it << " ";
    cout << endl;
}

void print2(set<int,greater<int> > s)
{
    set<int>::iterator it;
    for (it = s.begin();it != s.end();it ++) cout << *it << " ";
    cout << endl;
}

int main()
{
    int a[] = {1,4,6,4,10,8};
    
    //set<int> s1 等价于 set<int,less<int> > s1(默认)
    set<int> s1(a,a + 6);
    set<int,less<int> > s2(a,a + 6);
    print1(s1);//1 4 6 8 10
    print1(s2);//1 4 6 8 10
    
    set<int,greater<int> > s3(a,a + 6);
    print2(s3);//10 8 6 4 1
    
    return 0;
}
SET的一些函数
  • s.find(x) —— 查找元素x的位置,返回的是这个元素所在位置的迭代器。如果没有找到这个元素,则返回s.end()
  • s.insert(x) —— 向集合中插入元素x
#include <iostream>
#include <set>
using namespace std;

void print(set<int> s)
{
    set<int>::iterator it;
    for (it = s.begin();it != s.end();it ++) cout << *it << " ";
    cout << endl;
}

int main()
{
    int a[] = {1,4,6,4,10,8};
    set<int> s(a,a + 6);
    print(s);//1 4 6 8 10
    
    s.insert(5);
    print(s);//1 4 5 6 8 10
    
    set<int>::iterator it;
    it = s.find(6);
    if (it != s.end()) cout << "find" << " " << *it << endl;//find 6
    else cout << "not find" << endl;
    return 0;
}
集合中存储结构体

利用集合有序的特征,通过重载运算符,可以实现对学生的成绩按照成绩降序(从大到小)排列,如果成绩相同,那么按照学号降序排列。

#include <iostream>
#include <set>
using namespace std;

struct student//学生结构体
{
    int num;//学号
    string name;//姓名
    int score;//分数
    
    //重载大于号
    //score是结构体student中的元素,s.score是集合s中的元素
    bool operator > (const student & s) const{
        //按照成绩降序排列,如果成绩相同,那么按照学号降序排列
        if ( (score > s.score) || (score == s.score && num > s.num) ) return true;
        else return false;
    }
};

int main()
{
    set<student,greater<student> > s;//学生类型的集合
    
    student st1 = {1,"yangyu",99};
    student st2 = {3,"wangwei",98};
    student st3 = {4,"xiaochu",100};
    student st4 = {2,"laohe",100};
    
    s.insert(st1); s.insert(st2); s.insert(st3); s.insert(st4);//插入数据
    
    set<student>::iterator it;//遍历集合并输出
    for (it = s.begin();it != s.end();it ++)
    {
        cout << it->num << " " << it->name << " " << it->score;
        cout << endl;
    }
    return 0;
}

输出如下:

4 xiaochu 100
2 laohe 100
1 yangyu 99
3 wangwei 98

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值