仿函數與函數適配器如何正確的在c++中使用?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
所謂的仿函數(functor),是通過重載()運算符模擬函數形為的類?! ?/p>
因此,這里需要明確兩點:
1 仿函數不是函數,它是個類;
2 仿函數重載了()運算符,使得它的對你可以像函數那樣子調用(代碼的形式好像是在調用函數)?! ?/p>
for_each
這里的for循環語句有點冗余,想到了std::for_each ,為了使用for_each,我們需要定義一個函數,如下:
void print( State* pstate )
{
pstate->print();
}于是就可以簡化為下面代碼:
std::for_each( vect.begin(), vect.end(), &print );
STL大致分為六大模塊:容器(container),算法(algorithm),迭代器(iterator),仿函數(functor),配接器(adapter),配置器(allocator)。其中仿函數是體積最小,觀念最簡單,但是在stl算法的搭配中起到了非常重要的作用,這是與簡單的lambda或者指針函數所不同的。
在stl中提供了大量有用的仿函數,比如plus,minus,multiplies,divides,modulus,equal_to,not_equal_to,greater…很多很多,根據傳入的參數的個數我們可以分為只需要接受一個參數的仿函數(unary_function)和需要接收兩個參數的仿函數(binary_function)。
仿函數實現示例
//仿函數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; //使用對象調用
cout << comp<int>()(1, 2) << endl; //使用仿函數實現在上面的代碼中,第一種調用方式是使用comp的定義的一個對象,然后通過這個對象來調用操作符(),來實現兩個數組的比較的;對于第二個調用comp()(1, 2)是產生一個臨時(無名的)對象。
2.2 仿函數詳細說明
在下面的使用場景(統計一個容器中的符合規定的元素),將說明之前提到的函數指針為什么不能在STL中替換掉仿函數
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);在上面我們傳遞進去了一個函數指針作為count_if的比較條件。但是現在根據新的需求,不再統計容器中小于5的變量個數,改為了8或者3。那么最直接的方法就是加一個參數threshold就可以了,就像下面這樣
bool my_count(int num, int threshold)
{
return (num < threshold));
}但是這樣的寫法STL中是不能使用的,而且當容器中的元素類型發生變化的時候就不能使用了,更要命的是不能使用模板函數。
那么,既然多傳遞傳遞參數不能使用,那就把需要傳遞進來的那個參數設置為全局的變量,那樣確實能夠實現當前情況下對閾值條件的修改,但是修改起來存在隱患(要是沒有初始化就調用怎么辦)。因而解決這樣問題的方式就是
方式就很好的兼容了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.仿函數當做排序準則
#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;
};//仿函數實現自定義排序
class PersonSortCriterion
{
public:
//仿函數
//排序規則為:按照lastname升序排列,lastname相同時按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[])
{
//類型重定義,并指定排序規則
typedef set<Person, PersonSortCriterion> PersonSet;
PersonSet col1;
//創建元素,并添加到容器
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;
}
有多種狀態的仿函數
#include <iostream>
#include <list>
#include<algorithm>
using namespace std;class IntSequence
{
private:
int value; //記錄內部狀態的成員變量
public:
IntSequence(int initialValue) : value(initialValue)
{
}
//仿函數
int operator()()
{
return value++;
}
};int main()
{
list<int> col1;
//產生長度為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個到倒數第2個,從42開始
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;
}
仿函數都是傳值,而不是傳址的。因此算法并不會改變隨參數而來的仿函數的狀態。
比如:
IntSequence seq(1); //從1開始的序列 //從1開始向容器col1中插入9個元素 generate_n(back_inserter(col1), 9, seq); //仍然從1開始向容器col1中插入9個元素 generate_n(back_inserter(col1), 9, seq);
generate函數
#include <iostream>
#include <algorithm>
#include <array>
#include <vector>
#include <functional>
using namespace std;
int main(){
array<int,8> t1; //產生序列個100內的隨機數
generate(t1.begin(),t1.end(),[](){return rand()%100;}); //產生5個1000內的隨機數
generate_n(t1.begin(),5,[](){return rand()%1000;});
for_each(t1.begin(),t1.end(),[](int i){cout<<i<<endl;});
return 0;
}當然,也有方法來解決上述使仿函數內部狀態改變的問題。
方法有兩種:
1、以引用的方式傳遞仿函數;
2、運用for_each()算法的返回值。
因為for_each()算法它返回其仿函數。也就是說,我們可以通過返回值可以取得仿函數的狀態。
以引用的方式傳遞仿函數
#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);
//采用引用類型
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;
//相當于重新構建一個對象從42開始插入4個元素
generate_n(back_inserter(col1),
4,
IntSequence(42));
//1 2 3 4; 42 43 44 45
for (auto t : col1) {
cout << t << " ";
}
cout << endl;
//前面使用的是引用類型,所以seq的內部狀態已經被改變了
//插值從上次完成后的5開始
//注意:這次調用仍然使用的是傳值類型
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;
//上一次調用使用的是傳值類型,所以這次還是從5開始插值
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;
}
運用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;
}
判斷式與仿函數
判斷式就是返回布爾型的函數或者仿函數。對于STL而言,并非所有返回布爾值的函數都是合法的判斷式。這可能會導致很多出人意料的行為,比如下例:
#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");
}
函數配接器(函數 適配器)
函數配接器:能夠將仿函數和另一個仿函數(或某個值,或某個一般函數)結合起來的仿函數。
函數配接器包含在頭文件<functional>中。預定義的函數配接器如下表所示:

先弄清幾個概念,什么叫一元函數,二元函數
1、一元函數一個參數
2、二元函數 兩個參數
3、一元謂詞 一個參數,返回類型為bool型
4、二元謂詞 兩個參數,返回類型為bool型
函數適配器是用來讓一個函數對象表現出另外一種類型的函數對象的特征。因為,許多情況下,我們所持有的函數對象或普通函數的參數個數或是返回值類型并不是我們想要的,這時候就需要函數適配器來為我們的函數進行適配
C++中有三類適配器,分別是容器適配器,迭代器適配器和函數適配器,這里主要介紹函數適配器。
函數適配器用于特化和擴展一元二元函數對象,函數適配器主要有以下兩類:
1 綁定器
該類適配器用于將二元函數適配成一元函數
將二元函數的一個參數綁定到一個特定的值上,將二元函數對象轉換成一元函數對象。
綁定器適配器有兩種:bind1st bind2nd。每個綁定器接受一個函數對象和一個值
bind1st將給定值綁定到二元函數對象的第一個實參
bind2nd將給定值綁定到二元函數對象的第二個實參
#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;
//計算奇數元素的個數
// 這里的bind2nd將二元函數對象modulus轉換為一元函數對象。
//bind2nd(op, value) (param)相當于op(param, value)
cout << count_if(v.begin(), v.end(),bind2nd(modulus<int>(), 2)) << endl; //bind1st(op, value)(param)相當于op(value, param);
//把4綁定為第一個參數,即 4 < value
//比4大的數字有幾個
cout << count_if(v.begin(), v.end(),bind1st(less<int>(), 4)) << endl; //把3綁定為第二個參數,即 value < 3
//比3小的數字有幾個
cout << count_if(v.begin(), v.end(), bind2nd (less<int>(), 3)) << endl; //把3綁定為第二個參數,即 value < 3
//not1 對第一個對象取反。
//對一元函數對象的結果取反
//比3小的數字有幾個的結果取反
cout << count_if(v.begin(), v.end(),not1( bind2nd (less<int>(), 3)) )<< endl;
system("pause");
return 0;
//輸出 3 3 1 2 3
}關于仿函數與函數適配器如何正確的在c++中使用問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。