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;
}
~~~