C++primer学习:泛型算法(3)

lambda表达式,lambda表达式有点类似于函数,它的格式是[capture list](parameter list) ->return type{function body;};

为什么要引入它呢?因为我们在使用谓词的时候只能接受一元或者两元谓词。如果需要传递更多的参数时没有任何办法的.这个时候就需要把原来的谓词实参改为lambda表达式.它可以通过capture list传递它所在的函数里面的局部变量.

练习:编写一个lambda,接受两个int,返回它们的和.

    auto f = [](const int &a, const int &b) {return a + b; };
    cout << f(12, 13) << endl;

练习:先将文本排序(按长度排序,长度相同的按字典顺序排序),消除重复元素,输出长度大于给定长度的元素.

//for_each也是一种算法,可以用for代替

void biggies(S &words, string::size_type sz)
{
    sort(words.begin(), words.end());//按字典顺序排序
    auto end = unique(words.begin(), words.end());//消除重复
    words.erase(end, words.end());//删除重复
    stable_sort(words.begin(), words.end(), 
        [](const string&s1, const string &s2){return s1.size() < s2.size(); });//按长度排序  
    //找到第一个
    auto wz = find_if(words.begin(), words.end(), [sz](const string&s){return s.size()>=sz; });

    auto count = words.end() - wz;//j计算个数
    cout << count << " words" << "of length " << sz <<" or longer"<< endl;
    for_each(wz, words.end(), [](const string &s){cout << s<<" "; });
    cout << endl;
}

======================================================================================

[1]bind():参数绑定.在接受谓词时候,除了lambda表达式,我们还可以用bind函数来传递参数. 它定义在头文件functional 中,以视作一个函数适配器.它接受一个可调用对象,生成一个新的可调用对象.

auto newCallable = bind(callable,arg_list);当我们调用newcallable对象时,newcallable会调用callable,并且把arg_list的参数传给它.参数列表可能含有_1,_2…_n等参数,它们是占位符,表示newCallable中的参数.

**//输出单词长度小于6的单词(用bind())

bool lessthan_sz(const string &s, int sz)
{
    return s.size() <= sz;
}
    vector<string> words{ "hello0000", "world", "I am", "pezy000000","pezy000000", "hello" };
    int sz = 6;
    cout << count_if(words.cbegin(), words.cend(), bind(lessthan_sz, _1, sz));
练习:利用bind找到在一个int的vector中查找到第一个大于strin长度的值.
bool check_size(const int len, const string &s)
{
    return len > s.size();
}
vector<int> vec{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int sz = 6;
    auto it = find_if(vec.cbegin(), vec.cend(), bind(check_size, _1,words[1]));
    cout << *it << endl;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值