记录下我在学习STL过程中一些笔记,本人忘性太大,不得不做笔记,还是两份笔记,一份纸张版,一份网络版...
#include <iostream>#include <string>#include <set>using namespace std;struct Student{ // 存储学生的姓名及四级分数 string name; int total;};class PS{ // 比较对象 public: bool operator()(const Student& st1,const Student& st2) // 写operator()函数 { return st1.name < st2.name; }};int main(){ Student student[3]={ {"hicjiajia",425}, {"jintiankaosijile",425}, {"buzhidaonengbunengguo",425} }; set<Student,PS> st; // 用自定义的比较对象(PS)声明一个set对象 st.insert(student[0]); st.insert(student[1]); st.insert(student[2]); set<Student>::iterator it=st.begin(); for (;it!=st.end();it++) { cout<<(*it).name<<" "<<(*it).total<<endl; } system("pause"); return 0;}
我们知道 set 容器它是有序的,所以在向容器插入数据的时候,set 容器会根据 operator<() 操作符进行排序,对于C++内置类型排序是没有问题的,但是本例中我们自定义了一个数据类型为student, 此时set容器就无法自动为我们排序了,因此我们需要自己定义 operator<() 实现student 类型的大小比较,对此有两种方法,一种是重写一个比叫对象(本例为PS),然后重写operator()函数 ,在函数中进行比较两个关键字的大小,上面的代码用的就是这种方法,至于为什么要这样写,我们来看一下 set 容器的原型:
template
在默认情况下,set容器使用less
第二种方法:在Student 中直接给出operator<()的实现,这种方法我觉得比较好理解,下面看代码:
#include <iostream>#include <string>#include <set>using namespace std;struct Student{ string name; int total; bool operator<(const Student& st)const //给出operator<()的定义,以便在插入容器时排序 { return this->name < st.name; }};int main(){ Student student[3]={ {"hicjiajia",425}, {"jintiankaosijile",425}, {"buzhidaonengbunengguo",425} }; set<Student> st; //注意这里,与第一段代码的写法区别 st.insert(student[0]); st.insert(student[1]); st.insert(student[2]); set<Student>::iterator it=st.begin(); for (;it!=st.end();it++) { cout<<(*it).name<<" "<<(*it).total<<endl; } system("pause"); return 0;}
原文链接: https://www.cnblogs.com/hicjiajia/archive/2010/12/18/1909998.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/18944
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!