boost bind嵌套使用

#include <boost/bind/bind.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <cassert>
void sample1() {
    const boost::array<int, 12> v = {
         1, 2, 3, 4, 5, 6, 7, 100, 99, 98, 97, 96
    };
    const std::size_t count0 = std::count_if(v.begin(), v.end(), [] (int x) { return 5 < x; } );
    const std::size_t count1 = std::count_if(v.begin(), v.end(), boost::bind(std::less<int>(), 5, boost::placeholders::_1) );
    assert(count0 == count1);
}
void sample2() {
    const boost::array<std::string, 3> v = {
          "We ", "are", " the champions!"
    };
    const std::size_t count0 = std::count_if(v.begin(), v.end(), [] (const std::string &str) { return str.empty(); } );
    const std::size_t count1 = std::count_if(v.begin(), v.end(), boost::bind(&std::string::empty, boost::placeholders::_1) );
    assert(count0 == count1);
}
void sample3() {
    const boost::array<std::string, 3> v = {
          "We ", "are", " the champions!"
    };
    const std::size_t count0 = std::count_if(v.begin(), v.end(), [] (const std::string &str) { return str.size() < 5; } );
    const std::size_t count1 = std::count_if(v.begin(), v.end(), boost::bind(std::less<std::size_t>(), boost::bind(&std::string::size, boost::placeholders::_1), 5) );
    assert(count0 == count1);
}
void sample4() {
    const auto twice = boost::bind(std::plus<int>(), boost::placeholders::_1, boost::placeholders::_1);
    assert(twice(2) == 4);
    const auto minus_from_second = boost::bind(std::minus<int>(), boost::placeholders::_2, boost::placeholders::_1);
    assert(minus_from_second(2, 4) == 2);
}
int main() {
    sample1();
    sample2();
    sample3();
    sample4();

    return 0;
}

编译:g++ -std=c++17 -g -o Test test.cpp -I ./ -I /opt/boost/boost_1_78_0 -L /opt/boost/boost_1_78_0/stage -pthread

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值