C++学习笔记(Day17 函数对象)

函数对象

  • 一个行为类似函数的对象

  • 可以没有参数,也可以带有若干参数

  • 其功能是获取一个值,或者改变操作的状态。

    • 普通函数就是函数对象

    • 重载了“()”运算符的类的实例是函数对象

函数对象概念图

例10-13、例10-14:

  • 使用两种方式定义表示乘法的函数对象

    • 通过定义普通函数(例10-13)

    • 通过重载类的“()”运算符(例10-14)

  • 用到以下算法:

  • template<class InputIterator, class Type, class BinaryFunction>
    Type accumulate(InputIterator first, InputIterator last, Type val, BinaryFunction binaryOp);
    
    对[first, last)区间内的数据进行累“加”,binaryOp为用二元函数对象表示的“加”运算符,val为累“加”的初值
例 10-13 
#include <iostream> 
#include <numeric> //包含数值算法头文件 
using namespace std; 
//定义一个普通函数 
int mult(int x, int y) { return x * y; }; 
int main() { 
 int a[] = { 1, 2, 3, 4, 5 }; 
 const int N = sizeof(a) / sizeof(int); 
 cout << "The result by multipling all elements in a is " 
 << accumulate(a, a + N, 1, mult) 
 << endl; 
 return 0; 
} 
例 10-14 
//10_14.cpp 
#include <iostream> 
#include <numeric> //包含数值算法头文件 
using namespace std; 
class MultClass{ //定义MultClass类 
public: 
 //重载操作符operator() 
int operator() (int x, int y) const { return x * y; } 
}; 
int main() { 
 int a[] = { 1, 2, 3, 4, 5 }; 
 const int N = sizeof(a) / sizeof(int); 
 cout << "The result by multipling all elements in a is " 
 << accumulate(a, a + N, 1, MultClass()) //将类multclass传递给通用算法 
 << endl; 
 return 0; 
} 

STL提供的函数对象

  • 用于算术运算的函数对象:

    • 一元函数对象(一个参数) :negate

    • 二元函数对象(两个参数) :plus、minus、multiplies、divides、modulus

  • 用于关系运算、逻辑运算的函数对象(要求返回值为bool)

    • 一元谓词(一个参数):logical_not

    • 二元谓词(两个参数):equalto、notequalto、greater、less、greaterequal、lessequal、logicaland、logical_or

例10-15 利用STL标准函数对象

//10_15.cpp
#include <iostream>   
#include <numeric>   //包含数值算法头文件
#include <functional>  //包含标准函数对象头文件
using namespace std;    
int main() {
    int a[] = { 1, 2, 3, 4, 5 };
    const int N = sizeof(a) / sizeof(int);
    cout << "The result by multipling all elements in A is “
            << accumulate(a, a + N, 1, multiplies<int>())
         << endl; //将标准函数对象传递给通用算法
    return 0;
}

例10-16利用STL中的二元谓词函数对象

// 10_16.cpp
#include <functional>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main() {
    int intArr[] = { 30, 90, 10, 40, 70, 50, 20, 80 };
    const int N = sizeof(intArr) / sizeof(int);
    vector<int> a(intArr, intArr + N);
    cout << "before sorting:" << endl;
    copy(a.begin(),a.end(),ostream_iterator<int>(cout,"\t"));
    cout << endl;

    sort(a.begin(), a.end(), greater<int>());

    cout << "after sorting:" << endl;
    copy(a.begin(),a.end(),ostream_iterator<int>(cout,"\t"));
    cout << endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值