淺析stl序列容器(map和set)的仿函數(shù)排序
問題:set是一個(gè)自動有序的集合容器,這是set的一個(gè)最實(shí)惠的性質(zhì),從小到大,只要你插入進(jìn)去,就有序了。但是,如果你不想要這個(gè)順序呢,是不是可以人為控制set容器
的元素順序呢?答案是,可以的,因?yàn)閟tl也是程序員設(shè)計(jì)的。
首先看stl的模板構(gòu)造函數(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的構(gòu)造函數(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元素是一個(gè)結(jié)構(gòu)體,你最好要設(shè)置你的仿函數(shù),不然set一般默認(rèn)是按第一個(gè)字段排序的,而我們的實(shí)際情況是想按序號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有相同的應(yīng)用,如果你想快速理解,那么把這篇文章中的set改成map就差不多了。
總之,有序的stl容器在工程中應(yīng)用什么方便和廣泛,但是當(dāng)我們需要自己的排序的時(shí)候,可以用仿函數(shù)來設(shè)置它!
您可能感興趣的文章
- 01-10判斷整數(shù)序列是否為二元查找樹的后序遍歷結(jié)果的解決方法
- 01-10求數(shù)組中最長遞增子序列的解決方法
- 01-10淺析Linux下精確控制時(shí)間的函數(shù)
- 01-10淺析C語言中sscanf 的用法
- 01-10淺析C語言中printf(),sprintf(),scanf(),sscanf()的用法和區(qū)別
- 01-10淺析C++中memset,memcpy,strcpy的區(qū)別
- 01-10淺析C/C++中被人誤解的SIZEOF
- 01-10淺析int*p[ ]與int(*p)[ ]的區(qū)別
- 01-10淺析C語言中assert的用法
- 01-10淺析C語言頭文件和庫的一些問題


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達(dá)
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達(dá)式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
隨機(jī)閱讀
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 04-02jquery與jsp,用jquery
- 01-10delphi制作wav文件的方法
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文