c++仿函數(shù)和函數(shù)適配器的使用詳解
所謂的仿函數(shù)(functor),是通過(guò)重載()運(yùn)算符模擬函數(shù)形為的類(lèi)?! ?/p>
因此,這里需要明確兩點(diǎn):
1 仿函數(shù)不是函數(shù),它是個(gè)類(lèi);
2 仿函數(shù)重載了()運(yùn)算符,使得它的對(duì)你可以像函數(shù)那樣子調(diào)用(代碼的形式好像是在調(diào)用函數(shù))。
for_each
這里的for循環(huán)語(yǔ)句有點(diǎn)冗余,想到了std::for_each ,為了使用for_each,我們需要定義一個(gè)函數(shù),如下:
void print( State* pstate )
{
pstate->print();
}
于是就可以簡(jiǎn)化為下面代碼:
std::for_each( vect.begin(), vect.end(), &print );
STL大致分為六大模塊:容器(container),算法(algorithm),迭代器(iterator),仿函數(shù)(functor),配接器(adapter),配置器(allocator)。其中仿函數(shù)是體積最小,觀念最簡(jiǎn)單,但是在stl算法的搭配中起到了非常重要的作用,這是與簡(jiǎn)單的lambda或者指針函數(shù)所不同的。
在stl中提供了大量有用的仿函數(shù),比如plus,minus,multiplies,divides,modulus,equal_to,not_equal_to,greater…很多很多,根據(jù)傳入的參數(shù)的個(gè)數(shù)我們可以分為只需要接受一個(gè)參數(shù)的仿函數(shù)(unary_function)和需要接收兩個(gè)參數(shù)的仿函數(shù)(binary_function)。
仿函數(shù)實(shí)現(xiàn)示例
//仿函數(shù)1,比較大小template<typename T> struct comp
{
bool operator()(T in1, T in2) const
{
return (in1>in2);
}
};comp<int> m_comp_objext;
cout << m_comp_objext(6, 3) << endl; //使用對(duì)象調(diào)用
cout << comp<int>()(1, 2) << endl; //使用仿函數(shù)實(shí)現(xiàn)
在上面的代碼中,第一種調(diào)用方式是使用comp的定義的一個(gè)對(duì)象,然后通過(guò)這個(gè)對(duì)象來(lái)調(diào)用操作符(),來(lái)實(shí)現(xiàn)兩個(gè)數(shù)組的比較的;對(duì)于第二個(gè)調(diào)用comp()(1, 2)是產(chǎn)生一個(gè)臨時(shí)(無(wú)名的)對(duì)象。
2.2 仿函數(shù)詳細(xì)說(shuō)明
在下面的使用場(chǎng)景(統(tǒng)計(jì)一個(gè)容器中的符合規(guī)定的元素),將說(shuō)明之前提到的函數(shù)指針為什么不能在STL中替換掉仿函數(shù)
bool my_count(int num)
{
return (num < 5);
}int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> v_a(a, a+10);
cout << "count: " << std::count_if(v_a.begin(), v_a.end(), my_count);
在上面我們傳遞進(jìn)去了一個(gè)函數(shù)指針作為count_if的比較條件。但是現(xiàn)在根據(jù)新的需求,不再統(tǒng)計(jì)容器中小于5的變量個(gè)數(shù),改為了8或者3。那么最直接的方法就是加一個(gè)參數(shù)threshold就可以了,就像下面這樣
bool my_count(int num, int threshold)
{
return (num < threshold));
}
但是這樣的寫(xiě)法STL中是不能使用的,而且當(dāng)容器中的元素類(lèi)型發(fā)生變化的時(shí)候就不能使用了,更要命的是不能使用模板函數(shù)。
那么,既然多傳遞傳遞參數(shù)不能使用,那就把需要傳遞進(jìn)來(lái)的那個(gè)參數(shù)設(shè)置為全局的變量,那樣確實(shí)能夠?qū)崿F(xiàn)當(dāng)前情況下對(duì)閾值條件的修改,但是修改起來(lái)存在隱患(要是沒(méi)有初始化就調(diào)用怎么辦)。因而解決這樣問(wèn)題的方式就是
方式就很好的兼容了STL。
template<typename T> struct my_count1
{
my_count1(T a)
{
threshold = a;
}
T threshold;
bool operator()(T num)
{
return (num < threshold);
}
};int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int> v_a(a, a+10);cout << "count: " << std::count_if(v_a.begin(), v_a.end(), my_count1<int>(8));
1.仿函數(shù)當(dāng)做排序準(zhǔn)則
#include <iostream>
#include <string>
#include <set>
#include <algorithm>
using namespace std;class Person
{
public:
Person(string a, string b) :
strFirstname(a), strLastname(b)
{}
public:
string firstname() const
{
return strFirstname;
}
string lastname() const
{
return strLastname;
}
private:
const string strFirstname;
const string strLastname;
};//仿函數(shù)實(shí)現(xiàn)自定義排序
class PersonSortCriterion
{
public:
//仿函數(shù)
//排序規(guī)則為:按照l(shuí)astname升序排列,lastname相同時(shí)按firstname升序排列
bool operator()(const Person &p1, const Person &p2)
{
return (p1.lastname() > p2.lastname() ||
((p2.lastname() <= p1.lastname()) &&
p1.firstname() > p2.firstname()));
}
};
int main(int argc, char *argv[])
{
//類(lèi)型重定義,并指定排序規(guī)則
typedef set<Person, PersonSortCriterion> PersonSet;
PersonSet col1;
//創(chuàng)建元素,并添加到容器
Person p1("Jay", "Chou");
Person p2("Robin", "Chou");
Person p3("Robin", "Lee");
Person p4("Bob", "Smith");
//向容器中插入元素
col1.insert(p1);
col1.insert(p2);
col1.insert(p3);
col1.insert(p4);
PersonSet::iterator pos;
//輸出PersonSet中的所有元素
for (pos = col1.begin(); pos != col1.end(); ++pos)
{
cout << pos->firstname() << " " << pos->lastname() << endl;
}
cout << endl;
system("pause");
return 0;
}

有多種狀態(tài)的仿函數(shù)
#include <iostream>
#include <list>
#include<algorithm>
using namespace std;class IntSequence
{
private:
int value; //記錄內(nèi)部狀態(tài)的成員變量
public:
IntSequence(int initialValue) : value(initialValue)
{
}
//仿函數(shù)
int operator()()
{
return value++;
}
};int main()
{
list<int> col1;
//產(chǎn)生長(zhǎng)度為9的序列,依次插值到col1容器的尾部
generate_n(back_inserter(col1),
9,
IntSequence(1));
//1 2 3 4 5 6 7 8 9
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
//替換col1容器中第2個(gè)到倒數(shù)第2個(gè),從42開(kāi)始
generate(++col1.begin(),
--col1.end(),
IntSequence(42));
//1 42 43 44 45 46 47 48 9
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
system("pause");
return 0;
}

仿函數(shù)都是傳值,而不是傳址的。因此算法并不會(huì)改變隨參數(shù)而來(lái)的仿函數(shù)的狀態(tài)。
比如:
IntSequence seq(1); //從1開(kāi)始的序列 //從1開(kāi)始向容器col1中插入9個(gè)元素 generate_n(back_inserter(col1), 9, seq); //仍然從1開(kāi)始向容器col1中插入9個(gè)元素 generate_n(back_inserter(col1), 9, seq);
generate函數(shù)
#include <iostream>
#include <algorithm>
#include <array>
#include <vector>
#include <functional>
using namespace std;
int main(){
array<int,8> t1; //產(chǎn)生序列個(gè)100內(nèi)的隨機(jī)數(shù)
generate(t1.begin(),t1.end(),[](){return rand()%100;}); //產(chǎn)生5個(gè)1000內(nèi)的隨機(jī)數(shù)
generate_n(t1.begin(),5,[](){return rand()%1000;});
for_each(t1.begin(),t1.end(),[](int i){cout<<i<<endl;});
return 0;
}
當(dāng)然,也有方法來(lái)解決上述使仿函數(shù)內(nèi)部狀態(tài)改變的問(wèn)題。
方法有兩種:
1、以引用的方式傳遞仿函數(shù);
2、運(yùn)用for_each()算法的返回值。
因?yàn)閒or_each()算法它返回其仿函數(shù)。也就是說(shuō),我們可以通過(guò)返回值可以取得仿函數(shù)的狀態(tài)。
以引用的方式傳遞仿函數(shù)
#include <iostream>
#include <list>
#include <algorithm>using namespace std;class IntSequence
{
private:
int value;
public:
IntSequence(int initValue) : value(initValue)
{} int operator()()
{
return value++;
}
};int main()
{
list<int> col1;
IntSequence seq(1);
//采用引用類(lèi)型
generate_n<back_insert_iterator<list<int> >,
int, IntSequence&>(back_inserter(col1),
4,
seq);
//1 2 3 4;
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
//相當(dāng)于重新構(gòu)建一個(gè)對(duì)象從42開(kāi)始插入4個(gè)元素
generate_n(back_inserter(col1),
4,
IntSequence(42));
//1 2 3 4; 42 43 44 45
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
//前面使用的是引用類(lèi)型,所以seq的內(nèi)部狀態(tài)已經(jīng)被改變了
//插值從上次完成后的5開(kāi)始
//注意:這次調(diào)用仍然使用的是傳值類(lèi)型
generate_n(back_inserter(col1),
4,
seq);
//1 2 3 4; 42 43 44 45; 5 6 7 8
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
//上一次調(diào)用使用的是傳值類(lèi)型,所以這次還是從5開(kāi)始插值
generate_n(back_inserter(col1),
4,
seq);
//1 2 3 4; 42 43 44 45; 5 6 7 8; 5 6 7 8
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
system("pause");
return 0;
}

運(yùn)用for_each()算法的返回值
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;class MeanValue
{
private:
long num;
long sum;
public:
MeanValue() : num(0), sum(0)
{}
void operator() (int elem)
{
num++;
sum += elem;
} double value()
{
return static_cast<double>(sum) / static_cast<double>(num);
}
};
class Meansum
{
private:
//long num;
long sum;
public:
Meansum() : sum(0)
{}
void operator() (int elem)
{ sum += elem;
} double value()
{
return sum;
}
};
int main()
{
vector<int> col1;
for (int i = 1; i <= 8; ++i)
{
col1.push_back(i);
}
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
MeanValue mv = for_each(col1.begin(), col1.end(), MeanValue());
Meansum sum = for_each(col1.begin(), col1.end(), Meansum());
cout << "Mean Value: " << mv.value() << endl;
cout << "Mean sum: " << sum.value() << endl;
system("pause");
return 0;
}

判斷式與仿函數(shù)
判斷式就是返回布爾型的函數(shù)或者仿函數(shù)。對(duì)于STL而言,并非所有返回布爾值的函數(shù)都是合法的判斷式。這可能會(huì)導(dǎo)致很多出人意料的行為,比如下例:
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;class Nth
{
private:
int nth;
int count;
public:
Nth(int n) : nth(n), count(0)
{
}
bool operator() (int)
{
return ++count == nth;
}
};
int main()
{
list<int> col1;
for (int i = 1; i <= 9; ++i)
{
col1.push_back(i);
}
//1 2 3 4 5 6 7 8 9
for (auto t : col1) {
cout << t << " ";
}
cout << endl; list<int>::iterator pos;
pos = remove_if(col1.begin(), col1.end(), Nth(3));
col1.erase(pos, col1.end());
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
system("pause");
}

函數(shù)配接器(函數(shù) 適配器)
函數(shù)配接器:能夠?qū)⒎潞瘮?shù)和另一個(gè)仿函數(shù)(或某個(gè)值,或某個(gè)一般函數(shù))結(jié)合起來(lái)的仿函數(shù)。
函數(shù)配接器包含在頭文件<functional>中。預(yù)定義的函數(shù)配接器如下表所示:

先弄清幾個(gè)概念,什么叫一元函數(shù),二元函數(shù)
1、一元函數(shù)一個(gè)參數(shù)
2、二元函數(shù) 兩個(gè)參數(shù)
3、一元謂詞 一個(gè)參數(shù),返回類(lèi)型為bool型
4、二元謂詞 兩個(gè)參數(shù),返回類(lèi)型為bool型
函數(shù)適配器是用來(lái)讓一個(gè)函數(shù)對(duì)象表現(xiàn)出另外一種類(lèi)型的函數(shù)對(duì)象的特征。因?yàn)?,許多情況下,我們所持有的函數(shù)對(duì)象或普通函數(shù)的參數(shù)個(gè)數(shù)或是返回值類(lèi)型并不是我們想要的,這時(shí)候就需要函數(shù)適配器來(lái)為我們的函數(shù)進(jìn)行適配
C++中有三類(lèi)適配器,分別是容器適配器,迭代器適配器和函數(shù)適配器,這里主要介紹函數(shù)適配器。
函數(shù)適配器用于特化和擴(kuò)展一元二元函數(shù)對(duì)象,函數(shù)適配器主要有以下兩類(lèi):
1 綁定器
該類(lèi)適配器用于將二元函數(shù)適配成一元函數(shù)
將二元函數(shù)的一個(gè)參數(shù)綁定到一個(gè)特定的值上,將二元函數(shù)對(duì)象轉(zhuǎn)換成一元函數(shù)對(duì)象。
綁定器適配器有兩種:bind1st bind2nd。每個(gè)綁定器接受一個(gè)函數(shù)對(duì)象和一個(gè)值
bind1st將給定值綁定到二元函數(shù)對(duì)象的第一個(gè)實(shí)參
bind2nd將給定值綁定到二元函數(shù)對(duì)象的第二個(gè)實(shí)參
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>using namespace std;bool is_odd(int n)
{
return n % 2 == 1;
}int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
vector<int> v(a, a + 5); cout << count_if(v.begin(), v.end(), is_odd) << endl;
//計(jì)算奇數(shù)元素的個(gè)數(shù)
// 這里的bind2nd將二元函數(shù)對(duì)象modulus轉(zhuǎn)換為一元函數(shù)對(duì)象。
//bind2nd(op, value) (param)相當(dāng)于op(param, value)
cout << count_if(v.begin(), v.end(),bind2nd(modulus<int>(), 2)) << endl; //bind1st(op, value)(param)相當(dāng)于op(value, param);
//把4綁定為第一個(gè)參數(shù),即 4 < value
//比4大的數(shù)字有幾個(gè)
cout << count_if(v.begin(), v.end(),bind1st(less<int>(), 4)) << endl; //把3綁定為第二個(gè)參數(shù),即 value < 3
//比3小的數(shù)字有幾個(gè)
cout << count_if(v.begin(), v.end(), bind2nd (less<int>(), 3)) << endl; //把3綁定為第二個(gè)參數(shù),即 value < 3
//not1 對(duì)第一個(gè)對(duì)象取反。
//對(duì)一元函數(shù)對(duì)象的結(jié)果取反
//比3小的數(shù)字有幾個(gè)的結(jié)果取反
cout << count_if(v.begin(), v.end(),not1( bind2nd (less<int>(), 3)) )<< endl;
system("pause");
return 0;
//輸出 3 3 1 2 3
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方歡迎留言討論,望不吝賜教。
相關(guān)文章
使用?c++?在?windows?上定時(shí)執(zhí)行一個(gè)函數(shù)的示例代碼
這篇文章主要介紹了使用c++在windows上穩(wěn)定定時(shí)執(zhí)行一個(gè)函數(shù),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
C++ Thread實(shí)現(xiàn)簡(jiǎn)單的socket多線程通信
本文主要介紹了C++ Thread實(shí)現(xiàn)簡(jiǎn)單的socket多線程通信,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
c++中冒號(hào)(:)和雙冒號(hào)(::)的使用說(shuō)明
以下是對(duì)c++中冒號(hào)和雙冒號(hào)的用法進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下2013-07-07
C++中memcpy和memmove的區(qū)別總結(jié)
這篇文章主要介紹了C++中memcpy和memmove的區(qū)別總結(jié),這個(gè)問(wèn)題經(jīng)常出現(xiàn)在C++的面試題目中,需要的朋友可以參考下2014-10-10
利用stream實(shí)現(xiàn)一個(gè)簡(jiǎn)單的http下載器
這篇文章主要介紹了利用stream實(shí)現(xiàn)一個(gè)簡(jiǎn)單的http下載器的相關(guān)資料,需要的朋友可以參考下2015-03-03
簡(jiǎn)要解讀C++的動(dòng)態(tài)和靜態(tài)關(guān)聯(lián)以及虛析構(gòu)函數(shù)
這篇文章主要介紹了簡(jiǎn)要解讀C++的動(dòng)態(tài)和靜態(tài)關(guān)聯(lián)以及虛析構(gòu)函數(shù),析構(gòu)函數(shù)在C++編程中平時(shí)并不是太常用,需要的朋友可以參考下2015-09-09
C語(yǔ)言中的內(nèi)存泄露 怎樣避免與檢測(cè)
堆經(jīng)常會(huì)出現(xiàn)兩種類(lèi)型的問(wèn)題:1.釋放或改寫(xiě)仍在使用的內(nèi)存(稱(chēng)為:“內(nèi)存損壞”)。2.未釋放不再使用的內(nèi)存(稱(chēng)為:“內(nèi)存泄露”)。這是最難被調(diào)試發(fā)現(xiàn)的問(wèn)題之一2013-09-09
最新VScode C/C++ 環(huán)境配置的詳細(xì)教程
這篇文章主要介紹了最新VScode C/C++ 環(huán)境配置的詳細(xì)教程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11

