64set容器-内置类型数据指定排序规则

#include<iostream>
#include<deque>
#include<vector>
#include<stack>
#include<algorithm>
#include<Queue>
#include<ctime>
#include<list>
#include<set>
using namespace std;
//set容器排序


class MyCompare
{
public:
	bool operator()(int a,int b) const
	{
		return a > b;
	}
};
void test01()
{
	set<int>s1;
	s1.insert(10);
	s1.insert(30);
	s1.insert(20);
	s1.insert(40);

	for (set<int>::iterator it = s1.begin(); it != s1.end(); it++)
	{
		cout << *it << " ";
	}

	cout << endl;

	//指定排序规则   从大到小
	set<int,MyCompare>s2;
	s2.insert(10);
	s2.insert(30);
	s2.insert(20);
	s2.insert(40);

	for (set<int, MyCompare>::iterator it = s2.begin(); it != s2.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
	
}
void test02() 
{
	
	
}

int main()
{

	test01();
	//test02();
	system("pause");
	return 0;
}

自定义类型数据排序

#include<iostream>
#include<deque>
#include<vector>
#include<stack>
#include<algorithm>
#include<Queue>
#include<ctime>
#include<list>
#include<set>
using namespace std;
//set容器排序

//自定义的数据类型  都会指定排序规则


class Person
{
public:
	Person(string name, int age)
	{
		this->m_Age = age;
		this->m_Name = name;
	}
	string m_Name;
	int m_Age;
};
class MyCompare
{
public:
	bool operator()(const Person &p1, const Person &p2) const
	{
		//按照年龄降序
		return p1.m_Age > p2.m_Age;
	}
};
void test01()
{
	set<Person, MyCompare>s;
	Person p1("A", 28);
	Person p2("D", 38);
	Person p3("H", 19);
	Person p4("C", 24);

	s.insert(p1);
	s.insert(p2);
	s.insert(p3);
	s.insert(p4);

	for (set<Person, MyCompare>::iterator it = s.begin(); it != s.end(); it++)
	{
		cout << "姓名:" << (*it).m_Name << " 年龄:" << (*it).m_Age << endl;
	}

}
void test02() 
{
	
	
}

int main()
{

	test01();
	//test02();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值