目录
自定义排序规则的multiset用法
前言:
在这个笔记中,我把大多数代码都加了注释,我的一些想法和注解用蓝色字体标记了出来,重点和需要关注的地方用红色字体标记了出来,只不过这一次的笔记主要是我的补充,全部使用蓝色字体就比较瞎眼了,所以这一次不会用蓝色字体。
书接前文,上次我们介绍了multiset的基本用法(C++STL标准库学习笔记(三)multiset),这里我们继续,介绍multiset的自定义排序规则用法和结构体的用法。
正文
1.1 自定义排序规则
先给上代码样例:
#include<set>
#include<iostream>
#include<cstring>
using namespace std;
struct rule1
{
bool operator()(const int & a,const int & b)
{
return (a%10) < (b%10);
}//返回值为true说明a必须排在b前面
};
int main(int argc, char const *argv[])
{
multiset<int,greater<int>>st;//排序规则为从大到小
int a[10] = {1,14,12,13,7,13,21,19,8,8};
for (int i = 0; i < 10; i++)
{
st.insert(a[i]);
}
multiset<int,greater<int>>::iterator i;
for (i = st.begin(); i != st.end(); i++)
{
cout<<*i<<",";//结果:21,19,14,13,13,12,8,8,7,1,
}
cout<<endl;
multiset<int,rule1>st2;
//st2的排序规则为:个位数小的排前面
for (int i = 0; i < 10; i++)
{
st2.insert(a[i]);
}
multiset<int,rule1>::iterator p;
for ( p = st2.begin(); p != st2.end(); p++)
{
cout<<*p<<",";//结果:1,21,12,13,13,14,7,8,8,19,
}//这里的结果就具有不确定性了,1和21谁在前面都可以的
cout<<endl;
p = st2.find(133);//经典,查找不是找==,而是找x<y和y<x都不成立的条件
//就是x既不在y前面,也不在y后面的情况
//这里的情况就是13和133按这个排序顺序是相同的,所以找得到
cout<<*p<<endl;//结果:13
return 0;
}
其中简单介绍一下几个重要的地方:
multiset<int,greater<int>>st;
multiset<int,greater<int>>::iterator i;
multiset<int,rule1>st2;
multiset<int,rule1>::iterator p;
可以看到它们的定义确实和之前使用sort时一模一样,需要强调的地方其实也差不多:
1、find()查找是按x既不在y前面,也不在y后面的规则来查找的,而不是找x == y。
2、排序顺序也是按自定义的来排,这个例子中的rule1并没有定义个位数相同时,十位数及以上怎么排序,所以14和13按这个规则排序谁在前面都有可能。
1.2 结构体及其自定义排序规则
也先给上代码样例:
#include<set>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
struct Student
{
char name[20];
int id;
int score;
};
Student students [] =
{
{"Jack",112,78},
{"Mary",102,85},
{"Ala",333,92},
{"Zero",101,70},
{"Cindy",102,78}
};
struct rule
{
bool operator()(const Student & s1,const Student & s2)
{
if (s1.score != s2.score)
{
return s1.score>s2.score;
}
else
{
return(strcmp(s1.name,s2.name) < 0);
}
}
};
int main(int argc, char const *argv[])
{
multiset<Student,rule> st;
for (int i = 0; i < 5; i++)
{
st.insert(students[i]);//插入的是students[i]的复制品
}
multiset<Student,rule>::iterator p;
for ( p = st.begin(); p != st.end(); p++)
{
cout<<p->score<<" "<<p->name<<" "<<p->id<<endl;
}
/*
结果:
92 Ala 333
85 Mary 102
78 Cindy 102
78 Jack 112
70 Zero 101
*/
Student s = {"Mary",1000,85};
p = st.find(s);
if (p!=st.end())
{
cout<<p->score<<" "<<p->name<<" "<<p->id<<endl;
}//结果:85 Mary 102
//因为我们没比较id,所以。。。找到了
//这里再次强调一次不是比==,而是比排序
return 0;
}
这里需要强调的其实也差不多:
multiset<Student,rule> st;
multiset<Student,rule>::iterator p;
例子中再次说明了查找不是找“==”,这里就不再赘述了。
后记:
这玩意确实可以融会贯通,用法都差不多,记住就行。感谢大家读到这里,祝大家学业有成,天天开心,不要又没摸着鱼,又没学到东西,那就不好了。(吐槽一下,这一篇好短,这就是摸鱼吗)