• C++之STL(十)


    1、适配器

    2、函数适配器

    1. #include
    2. using namespace std;
    3. #include
    4. #include
    5. #include
    6. bool isOdd(int n)
    7. {
    8. return n % 2 == 1;
    9. }
    10. int main() {
    11. int a[] = {1, 2, 3, 4, 5};
    12. vector <int> v(a, a + 5);
    13. cout << count_if(v.begin(), v.end(), isOdd) << endl;
    14. // binder2nd将二元函数对象modulus转换为医院函数对象。
    15. // binder2nd(op, value)(param)相当于op(param, value)
    16. cout << count_if(v.begin(), v.end(), binder2nd(modulus<int>(), 2)) << endl;
    17. // binder1st(op, value)(param)相当于op(value, param)
    18. cout << count_if(v.begin(), v.end(), binder1st(less<int>(), 4)) << endl;
    19. return 0;
    20. }
    21. // 输出
    22. 3
    23. 3
    24. 1

    3、针对成员函数的函数适配器

    1. #include
    2. using namespace std;
    3. #include
    4. #include
    5. #include
    6. #include
    7. class Person
    8. {
    9. public:
    10. Person(const string& name) : name_(name)
    11. {
    12. }
    13. void print() const
    14. {
    15. cout << name_ << endl;
    16. }
    17. void printWithPrefix(string prefix) const
    18. {
    19. cout << prefix << name_ << endl;
    20. }
    21. private:
    22. string name_;
    23. };
    24. void foo(const vector& v)
    25. {
    26. for_each(v.begin(), v.end(), mem_fun_ref(&Person::print));
    27. for_each(v.begin(), v.end(), binder2nd(mem_fun_ref(&Person::printWithPrefix), "Person: "));
    28. }
    29. void foo2(const vector& v)
    30. {
    31. for_each(v.begin(), v.end(), mem_fun(&Person::print));
    32. for_each(v.begin(), v.end(), binder2nd(mem_fun(&Person::printWithPrefix), "Person: "));
    33. }
    34. int main() {
    35. vector v;
    36. v.push_back(Person("tom"));
    37. v.push_back(Person("jer"));
    38. foo(v);
    39. vector v2;
    40. v2.push_back(new Person("tom"));
    41. v2.push_back(new Person("jer"));
    42. foo2(v2);
    43. return 0;
    44. }
    45. // 输出
    46. tom
    47. jer
    48. Person: tom
    49. Person: jer
    50. tom
    51. jer
    52. Person: tom
    53. Person: jer

    4、针对一般函数的函数适配器

    1. #include
    2. using namespace std;
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. int main() {
    9. char* a[] = {"", "BBB", "CCC"};
    10. vector<char*> v(a, a + 2);
    11. vector<char*>::iterator it;
    12. it = find_if(v.begin(), v.end(), binder2nd(ptr_fun(strcmp), ""));
    13. if (it != v.end())
    14. {
    15. cout << *it << endl;
    16. }
    17. return 0;
    18. }
    19. // 输出
    20. BBB
  • 相关阅读:
    Python图像处理丨带你掌握图像几何变换
    go初识iris框架(五) -MVC包的使用
    App移动端测试(3)—— ADB命令
    Spring-Cloud-Openfeign如何传递用户信息?
    路线中桩测量计算程序浅析
    Mysql锁相关知识补充
    uniapp微信小程序授权获得手机号
    计算机起源(二)
    线性代数学习笔记11-2:总复习Part2(相似对角化、对称矩阵、奇异值分解SVD)
    【小月电子】FPGA开发板(XLOGIC_V1)系统学习教程-LESSON10
  • 原文地址:https://blog.csdn.net/CSDN_HZW/article/details/140008320