标准库定义的函数对象--接“将函数对象用于标准库算法”

来源:互联网 发布:淘宝开店类目怎么选 编辑:程序博客网 时间:2024/09/21 06:19

标准库<functional>头文件中定义了一组类似于前边的GT_cls的函数对象。奇怪的是不需要include<functional>(mark)

有一元函数对象:一元减minus<Type>和逻辑非logical_not<Type>

其余都是二元函数对象

一个简单实例:

chap/functionObject.cpp

#include"head.h"//#include<functional>int main(){std::plus<int> intAdd;//function object that can add two int values.二元加std::negate<int> intNegate;//function object that can negate an int value/一元减//uses intAdd::operator(int, int) to add 10 and 20int sum = intAdd(10, 20);std::cout << sum << std::endl;//uses intNegate::operator(int) to generate -10 as second parameter//to intAdd::operator(int, int)sum = intAdd(10, intNegate(11));std::cout << sum << std::endl;//在算法中使用标准库函数对象std::vector<std::string> words(3, "fuck");words.push_back("killer");words.push_back("kiss");words.push_back("kif");words.push_back("asdad");for(std::vector<std::string>::iterator iter = words.begin(); iter != words.end(); iter++)std::cout << *iter << "\t";std::cout << std::endl << "After sort():" << std::endl;sort(words.begin(), words.end());//正常:operator< 按字符串(字母)升序for(std::vector<std::string>::iterator iter = words.begin(); iter != words.end(); iter++)std::cout << *iter << "\t";std::cout << std::endl << "After sort(b, e, greater<Type>):" << std::endl;//类似于GT_cls,不过后者是返回bool类型以供判断,//前者是要代替特定的(以operator<(也是返回bool估计,根据bool做排序)做升序排列的操作),达到以别的方式做升降序(严格来讲就是根据bool排序)排列sort(words.begin(), words.end(), std::greater<std::string>());//定制:greater<string> stands for operator<  按字符串(字母)降序for(std::vector<std::string>::iterator iter = words.begin(); iter != words.end(); iter++)std::cout << *iter << "\t";}


function adapter 函数适配器

//函数对象的函数适配器#include"head.h"int main(){    //绑定器binder:bind1st,bind2nd;绑定一个现成的实参到二元函数对象函数第一个或第二个参数,使之变成一元函数    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};    std::vector<int> vec(a, a + 10);    std::cout << count_if(vec.begin(), vec.end(), std::bind2nd(std::less_equal<int>(), 7)) << std::endl;    //less_equal<Type> 不支持std::string类型        //求反器negator:not1,not2;将一元函数对象或二元函数对象的真值求反    //求反与绑定的嵌套使用    std::cout << count_if(vec.begin(), vec.end(), not1(std::bind2nd(std::less_equal<int>(), 7))) << std::endl;    }

pe14_37.cpp