set容器存储自定义类型数据

#include <iostream>
using namespace std;
#include <set>
class Student
{
public:
	Student(char*name,int age)
	{
		strcpy(this->name,name);
		this->age=age;
	}
public:
	int age;
	char name[64];
};

//仿函数
struct FuncStudent
{
	bool operator()(const Student&left,const Student &right)
	{
		if(left.age<right.age)//如果左边的值小就返回真,即从小到大安装年龄排序
		{
			return true;
		}
		else
		{
			return false;
		}
	}
};

int main()
{
	Student s1("s1",31);
	Student s2("s2",22);
	Student s3("s3",44);
	Student s4("s4",11);

	set<Student,FuncStudent> set1;
	set1.insert(s1);
	set1.insert(s2);
	set1.insert(s3);
	set1.insert(s4);

	//遍历
	for(set<Student,FuncStudent>::iterator it=set1.begin();it!=set1.end();it++)
	{
		cout<<it->age<<"\t"<<it->name<<endl;
	}

	system("pause");
	return 0;
}



Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐