牛骨文教育服务平台(让学习变的简单)

STL中的set和map是有序容器,使用时如果希望根据自己的需要来设定排序器,通常有一下两种方式。

1.如果容器中直接存储对象的话,那么我们可以在对象类中重载<即可,内置类型的话就不需要了,因为有默认的

2.如果存储的不是直接对象的话比如对象的指针(通常为智能指针),这个时候我们就要定义自己的比较器。而比较器的写法一般有两种。

->1.类内重载函数调用运算符的方法。

->2.以函数的方式提供比较器。

对于第一种方法是非常简单而且经常用的,这里不再赘述。

下面主要以一个简单的例子来介绍第二种方法中比较器的两种写法(这里为了方便说明,暂时存储对象)。

student.h

class Student{
public:
	Student(const string &sid) : id(sid){}

	void print()const{
		cout << id << endl;
	}

	string getId()const{
		return id;
	}

private:
	string id;
};

main.cpp

struct Compare{
	//override the operator ()
	bool operator()(const Student &ls, const Student &rs)const{
		return ls.getId() < rs.getId();
	}
};

bool compare(const Student &ls, const Student &rs){
	return ls.getId() < rs.getId();
}

int main(){
	/*the first type-----define a class as the comparator*/
	set<Student, Compare> ms;

	ms.insert(Student("222"));
	ms.insert(Student("111"));
	ms.insert(Student("333"));

	auto ite = ms.begin();

	for (; ite != ms.end(); ++ite){
		ite->print();
	}

	/*the second type----define a function as the comparator*/
	/*
	set<Student, bool (*)(const Student &ls, const Student &rs)> ms(compare);

	ms.insert(Student("222"));
	ms.insert(Student("111"));
	ms.insert(Student("333"));

	auto ite = ms.begin();

	for (; ite != ms.end(); ++ite){
		ite->print();
	}
	*/
	return 0;
}