当前位置:   article > 正文

预定义函数对象

预定义函数
  1. #include <iostream>
  2. #include<string>
  3. #include <vector>
  4. #include <list>
  5. #include <set>
  6. #include <map>
  7. #include <algorithm>
  8. #include <functional>
  9. using namespace std;
  10. //plus 预定义函数对象 能实现不能类型数据的+运算
  11. // 实现了算法和数据类型的分离 ===》通过函数对象技术实现的
  12. /*
  13. template<class _Ty>
  14. struct plus
  15. : public binary_function<_Ty, _Ty, _Ty>
  16. { // functor for operator+
  17. _Ty operator()(const _Ty& _Left, const _Ty& _Right) const
  18. { // apply operator+ to operands
  19. return (_Left + _Right);
  20. }
  21. };
  22. */
  23. void display()
  24. {
  25. plus<int> intadd;
  26. int x = 10l;
  27. int y = 200;
  28. int z = intadd(x,y);
  29. cout<<z<<endl;
  30. plus<string> stringadd;
  31. string s1 = "aaaa";
  32. string s2 = "bbbb";
  33. string s3 = stringadd(s1,s2);
  34. cout<<s3<<endl;
  35. cout<<"---------------"<<endl;
  36. /*
  37. template<class _RanIt,
  38. class _Pr> inline
  39. void sort(_RanIt _First, _RanIt _Last, _Pr _Pred)
  40. { // order [_First, _Last), using _Pred
  41. _DEBUG_RANGE(_First, _Last);
  42. _DEBUG_POINTER(_Pred);
  43. _Sort(_Unchecked(_First), _Unchecked(_Last), _Last - _First, _Pred);
  44. }
  45. */
  46. vector<string> v;
  47. v.push_back("dddd");
  48. v.push_back("aaaa");
  49. v.push_back("cccc");
  50. v.push_back("cccc");
  51. v.push_back("bbbb");
  52. sort(v.begin(),v.end(),greater<string>());
  53. for (vector<string>::iterator it = v.begin();it!=v.end();it++)
  54. {
  55. cout<<*it<<endl;
  56. }
  57. //统计和字符串相等的个数
  58. //equal_to<string> 有两个参数 left参数来自容器,right参数来自sc;
  59. //bind2nd函数适配器 把预定义函数对象和第二个参数进行绑定
  60. string sc = "cccc";
  61. int num = count_if(v.begin(),v.end(),bind2nd(equal_to<string>(),sc));
  62. cout<<num<<endl;
  63. }
  64. int main()
  65. {
  66. display();
  67. system("pause");
  68. return 0;
  69. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/589679
推荐阅读
相关标签
  

闽ICP备14008679号