stl算法设计理念_预定义函数对象和函数适配器1

来源:互联网 发布:逆矩阵怎么求 编辑:程序博客网 时间:2024/05/18 00:06

传智扫地僧课程学习笔记。


#include <iostream>using namespace std;#include "string"#include <vector>#include <list>#include "set"#include <algorithm>#include "functional"//plus<int> 预定义好的函数对象 能实现不同类型的数据的 + 运算//实现了 数据类型 和算法的分离 ===》通过函数对象技术实现的。。。。//思考:怎么样知道 plus<type> 是两个参数void main21(){/*template<class _Ty>struct plus: public binary_function<_Ty, _Ty, _Ty>{// functor for operator+_Ty operator()(const _Ty& _Left, const _Ty& _Right) const{// apply operator+ to operandsreturn (_Left + _Right);}};*/plus<int> intAdd;int x = 10; int y = 20;int z = intAdd(x, y); // x + y cout << "z:" << z << endl;plus<string> stringAdd;string s1 = "aaa";string s2 = "bbb";string s3 = stringAdd(s1, s2);cout << "s3:" << s3 << endl;vector<string> v1;v1.push_back("bbb");v1.push_back("aaa");v1.push_back("ccc");v1.push_back("zzz");v1.push_back("ccc");v1.push_back("ccc");/*template<class _Ty>struct greater: public binary_function<_Ty, _Ty, bool>{// functor for operator>bool operator()(const _Ty& _Left, const _Ty& _Right) const{// apply operator> to operandsreturn (_Left > _Right);}};*/sort(v1.begin(), v1.end(), greater<string>() );for (vector<string>::iterator it=v1.begin(); it!=v1.end(); it++){cout << *it << endl;}//求 ccc 出现的个数string sc = "ccc";//equal_to<string>() 有两个参数 left参数来自容器,right参数来自sc//bind2nd函数适配器 :把预定义函数对象 和 第二个参数进行绑定int num = count_if(v1.begin(), v1.end(), bind2nd(equal_to<string>(), sc) );cout << "num: " << num << endl;}


0 0