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;

你可能感兴趣的:(C++primer学习:泛型算法(3))