c 仿函式的應用

2021-06-02 14:06:28 字數 1869 閱讀 8542

首先介紹乙個簡單的例子

問題描述:

struct strecorditem

;listlistrecorditem;

現在要按照 ncount 降序,在 ncount 相同的時候,按btitemlvl的降序排列。

解決方法:

struct cmp

node;

vectornodetable;//can be sorted;

//仿函式,用於find_if,偵測字元是否已經存在;

//template class comparer : public binary_function;

const bool operator()(const vector::value_type& node, char ch) const

private:

char _ch;

};};

huffman.cpp

#include "huffman.h" 

huffman::huffman(void)

void huffman::encode(const string& file)

); if (result == nodetable.end())

else

}

else

}

fin.close();

//huffman tree;

}

void huffman::decode(const string& file, const string& srctable) const

huffman::~huffman(void)

說明:

1、仿函式不是函式,而是乙個類,這個類過載了()操作符;

2、仿函式呼叫過程是這樣的:find_if(nodetable.begin(), nodetable.end(), comparer(ch))

中 comparer(ch)只是建立了 comparer 類的匿名方法,過載的 operator() 真正的呼叫是在

接下來將要看到的 find_if 模板函式的這一句 pred(*first);

3、**中不使用 find 而使用 find_if 是因為需要進行查詢的不是 prime type 而是自行編寫的符合

templateinputiterator find_if ( inputiterator first, inputiterator last, predicate pred )  

4、bind2nd 函式的作用是將 二元運算元(binary functor, bf) 轉化為一元運算元(unary functor,uf)還有乙個類似的bind1st,

使用時需要包含functional標頭檔案;

5、進行比較的仿函式需要繼承 binary_functor,原型如下:

templatestruct binary_function 

;

還有一些比較有用的部落格,可以借鑑參考:

//介紹了一些stl的仿函式的應用

//實現了乙個泛化的仿函式

//詳細介紹了stl原始碼中對仿函式的使用並解析了remove_if、bind2nd的源**(個人覺得非常具有參考性,推薦閱讀)

//實現了乙個泛化的仿函式(>、<、== 、!=)的比較。

仿函式 C 中仿函式的應用

仿函式 c 中仿函式的應用 在使用仿函式的時候,主要用到以下兩種 一種是以基類std unary function派生出來的派生類 另一種是以基類std binary function派生出來的派生類。而這兩種有什麼區別呢?它們之間的區別只是第一種接收的引數個數為乙個,而第二種接收的引數的個數為兩個...

仿函式及其應用案例(C )

仿函式即是對 的過載,因為其呼叫方式很像函式,因此被稱為仿函式。class myadd int main 輸出結果為20 定義乙個類,資料成員包括姓名 年齡 身高。按照年齡對他們進行排序,年齡相同的,再按照身高進行排序。include include using namespace std 定義類 ...

python 仿函式 C 仿函式

c 的標準庫stl裡面有6大部件,其中之一為仿函式。初始看到這一名字可能讓人摸不著頭腦 函式倒是挺容易理解,何故又起個仿函式的名字呢?本文將帶你揭開它看起來挺讓人迷惑但是實際上很簡單的面紗。仿函式,看名字就知道它肯定和函式有什麼關聯,但是也肯定和函式有什麼區別。函式主要是一塊接收輸入引數然後按照一定...