您的位置:首页 > 编程语言 > C语言/C++

C++_set容器_知识点整理1

2020-02-29 20:05 330 查看
set<int,lesss<int>> SetIntA; //该容器是按升序方式排列元素。
set<int,greater<int>> SetIntB; //该容器是按降序方式排列元素。
set<int> 相当于 set<int,less<int>>
less<int> 与greater<int> 中的int 可以改成其它类型,该类型主要跟set容器的数据类型一致。
less<> 与 greater<> 是系统(ATL)提前为我们定义好的函数对象。
如何set不包含int类型,而包含自定义,要写自己的func函数。
set 里面值是唯一的,若值相等,则后者插入不成功。
STL的返回值很重要,如何正确的使用函数的返回值才是学习的关键及重点。
class Teacher
{
public:
char name[32];
int  age;
public:
Teacher(char *name, int age)
{
strcpy(this->name,name);
this->age = age;
}
~Teacher()
{
;
}
};
struct FuncTeacher
{
bool operator()(const Teacher& left, const Teacher& right)
{
if(left.age > right.age)
{
return true;
}
else
{
return false;
}
}
};
void SetTeacherPlay01(set<Teacher,FuncTeacher> & Set1)
{
Teacher t1("xiaolong",11);
Teacher t2("xiaodong",22);
Teacher t3("xiaohong",33);
Teacher t4("xiaobang",44);
Teacher t5("xiaoabai",11);
//typedef pair<iterator, bool> _Pairib;
pair<set<Teacher,FuncTeacher>::iterator,bool> Pair1 = Set1.insert(t2);
if(Pair1.second == true)
{
cout << "set Pair1 插入成功: " << endl;
}
else
{
cout << "set Pair1 插入失败: " << endl;
}
Set1.insert(t1);
Set1.insert(t3);
Set1.insert(t4);
pair<set<Teacher,FuncTeacher>::iterator,bool> Pair5 = Set1.insert(t5);
if(Pair5.second == true)
{
cout << "set Pair5 插入成功: " << endl;
}
else
{
cout << "set Pair5 插入失败: " << endl;
}
//遍历
for(set<Teacher,FuncTeacher>::iterator it = Set1.begin(); it != Set1.end(); it++)
{
cout << it->age << it->name << endl;
}
}
int main()
{
set<Teacher,FuncTeacher> Set1;
SetTeacherPlay01(Set1);
return 0;
}

  • 点赞
  • 收藏
  • 分享
  • 文章举报
逆天的小屁孩 发布了1 篇原创文章 · 获赞 0 · 访问量 106 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: