<STL> set随笔

记录下我在学习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 <class Key, class Compare=less<Key>, class Alloc=STL_DEFAULT_ALLOCATOR(Key) >
在默认情况下,set容器使用less<key>进行比较,这里我们自己写一个比较对象,显示覆盖它的第二个参数就可以达到目的。

第二种方法:在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/p/1909998.html