c++仿函数和函数适配器的使用详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c++仿函数和函数适配器的使用详解

coolwriter   2020-12-10 我要评论

所谓的仿函数(functor),是通过重载()运算符模拟函数形为的类。  

因此,这里需要明确两点:  

1 仿函数不是函数,它是个类;  

2 仿函数重载了()运算符,使得它的对你可以像函数那样子调用(代码的形式好像是在调用函数)。  

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
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方欢迎留言讨论,望不吝赐教。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们