文档详情

C语言程序设计(第4版)清华大学出版社c10.ppt

发布:2017-12-05约1.07万字共51页下载文档
文本预览下载声明
函数对象 函数对象 一个行为类似函数的对象 可以没有参数,也可以带有若干参数 其功能是获取一个值,或者改变操作的状态。 例 普通函数就是函数对象 重载了“()”运算符的类的实例是函数对象 * 函数对象 例10-13、例10-14 使用两种方式定义表示乘法的函数对象 通过定义普通函数(例10-13) 通过重载类的“()”运算符(例10-14) 用到以下算法: templateclass InputIterator, class Type, class BinaryFunction Type accumulate(InputIterator first, InputIterator last, Type val, BinaryFunction binaryOp); 对[first, last)区间内的数据进行累“加”,binaryOp为用二元函数对象表示的“加”运算符,val为累“加”的初值 * 函数对象 * #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-13:使用普通函数 * #include iostream #include numeric //包含数值算法头文件 using namespace std; class MultClass { public: 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()) endl; return 0; } 例10-14:重载“()”运算符 函数对象概念图 * 函数对象 (Function) 一元函数对象(Unary Function) 二元函数对象(Binary Function) 产生器 (Generator) 一元谓词 (Unary Predicate) 二元谓词 (Binary Predicate) 函数对象 STL提供的函数对象 用于算术运算的函数对象: 一元函数对象:negate 二元函数对象:plus、minus、multiplies、divides、modulus 用于关系运算、逻辑运算的函数对象 一元谓词:logical_not 二元谓词:equal_to、not_equal_to、greater、less、greater_equal、less_equal、logical_and、logical_or * 函数对象 函数适配器 绑定适配器 将n元函数对象的指定参数绑定为一个常数,得到n-1元函数对象:bind1st、bind2nd 组合适配器 将指定谓词的结果取反:not1、not2 指针函数适配器 对一般函数指针使用,使之能够作为其它函数适配器的输入:ptr_fun 成员函数适配器 对成员函数指针使用,把n元成员函数适配为n + 1元函数对象,该函数对象的第一个参数为调用该成员函数时的目的对象:ptr_fun、ptr_fun_ref * 函数对象 例10-17 * //包含的头文件略去…… int main() { int intArr[] = { 30, 90, 10, 40, 70, 50, 20, 80 }; const int N = sizeof(intArr) / sizeof(int); vectorint a(intArr, intArr + N); vectorint::iterator p = find_if(a.begin(), a.end(), bind2nd(greaterint(), 40)); if (p == a.end()) cout no element greater than 40 e
显示全部
相似文档