在看c++ Primer 关于泛型编程的章节中,看到了lambda和bind两个函数表达式。 书上说这些表达式都会被编译器隐含的转为函数对象类,然后默认生成一个此函数类的对象。
lambda表达式是在一元谓词和二元谓词无法满足一些情况下创建的。
表达式简介,在函数中用lambda可以很好的利用函数的局部变量。
例如下面的函数:
void elimDups(vector<string> &words)
{
sort(words.begin(), words.end());
auto end_unique = unique(words.begin(), words.end());
words.erase(end_unique, words.end());
}
void biggies(vector<string> &words, vector<string>:: size_type sz)
{
elimDups(words);
stable_sort(words.begin(), words.end(), [](const string &a, const string &b)
{ return a.size()<b.size();});
auto wc = find_if(words.begin(), words.end(), [sz](const string &a){return a.size() >= sz;});
auto count = words.end() - wc;
cout << count <<" "<< "word" <<"of length "<<sz<< " or longer"<<endl;
for_each(wc, words.end(), [](const string &s){cout << s << " ";});
cout << endl;
}
对于find_if函数,只可以接收一元谓词。此时可以用lambda表达式来捕获参数列表。
lambda表达式的一般结构
[capture list](parameter list) -> return type {function body}
bind 函数可以看作是一个通用的函数适配器,也就是任何函数都可以作为其参数。
调用bind的一般形式为:
auto newCallable = bind(callable, arg_list);
bool check_size(const string &s, string::size_type sz)
{
return a.siez() >= sz;
}
auto wc = find_if(words.begin(), words.end(), [sz](const string &a)
auto wc = find_if(words.begin(), words.end(), bind(check_size, _1, sz));