淺析stl序列容器(map和set)的仿函數(shù)排序
問題:set是一個自動有序的集合容器,這是set的一個最實惠的性質,從小到大,只要你插入進去,就有序了。但是,如果你不想要這個順序呢,是不是可以人為控制set容器
的元素順序呢?答案是,可以的,因為stl也是程序員設計的。
首先看stl的模板構造函數(shù)
explicit set ( const Compare& comp = Compare(), const Allocator& = Allocator() );
template
set ( InputIterator first, InputIterator last, const Compare& comp = Compare(), const Allocator& = Allocator() );
set ( const set& x );
我們完全可以重定義set的構造函數(shù)里的比較函數(shù),完成對set的自排序功能。
舉例:
bool fncomp (int lhs, int rhs) {return lhs
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs>rhs;} // 控制set逆序
};
void testset()
{
// 第一種使用方法
bool(*fn_pt)(int,int) = fncomp;
set sixth (fn_pt);
// 第二中使用方法
set s; // class as Compare
s.insert(4);
s.insert(5);
set::iterator it;
for(it=s.begin();it!=s.end();it++)
{
cout<<*it<<" ";
}
cout <<endl;
};
注意:如果set元素是一個結構體,你最好要設置你的仿函數(shù),不然set一般默認是按第一個字段排序的,而我們的實際情況是想按序號i排序:
struct ST_Message
{
public:
ST_Message(int seq, int64_t time, string strfrom, string strto, string strinfo){
this->seq=seq;this->time=time;this->strfrom=strfrom;this->strto=strto;this->strinfo=strinfo;}
int seq;
int64_t time;
string strfrom;
string strto;
string strinfo;
bool operator <(const ST_Message& other) const // 注意是const函數(shù)
{
if (seq != other.seq) // dtime按升序排序
{
return (seq < other.seq);
}
else if(time < other.time)
{
return (time < other.time);
}
else if(strcmp(strfrom.c_str(), other.strfrom.c_str()) != 0)
{
return (strcmp(strfrom.c_str(), other.strfrom.c_str()) < 0);
}
else if(strcmp(strto.c_str(), other.strto.c_str()) != 0)
{
return (strcmp(strto.c_str(), other.strto.c_str()) < 0);
}
else
{
return (strcmp(strinfo.c_str(), other.strinfo.c_str()) < 0);
}
}
};
stl中自動有序的容器map也和set有相同的應用,如果你想快速理解,那么把這篇文章中的set改成map就差不多了。
總之,有序的stl容器在工程中應用什么方便和廣泛,但是當我們需要自己的排序的時候,可以用仿函數(shù)來設置它!
相關文章
Visual Studio Code 2020安裝教程及CPP環(huán)境配置(教程圖解)
這篇文章主要介紹了Visual Studio Code 2020安裝教程、CPP環(huán)境配置,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03C++實現(xiàn)LeetCode(152.求最大子數(shù)組乘積)
這篇文章主要介紹了C++實現(xiàn)LeetCode(152.求最大子數(shù)組乘積),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07