C++11终于知道要在语言中加入匿名函数了。匿名函数在很多时候可以为编码提供便利,这在下文会提到。很多语言中的匿名函数,如C++,都是用Lambda表达式实现的。Lambda表达式又称为lambda函数。我在下文中称之为Lambda函数。
Lambda函数的用处
#include <string>
#include <vector>class AddressBook
{
public:
// using a template allows us to ignore the differences between functors, function pointers
// and lambda
template<typename Func>
std::vector<std::string> findMatchingAddresses (Func func)
{
std::vector<std::string> results;
for ( auto itr = _addresses.begin(), end = _addresses.end(); itr != end; ++itr )
{
// call the function passed into findMatchingAddresses and see if it matches
if ( func( *itr ) )
{
results.push_back( *itr );
}
}
return results;
}private:
std::vector<std::string> _addresses;
};
AddressBook global_address_book;
vector<string> findAddressesFromOrgs ()
{
return global_address_book.findMatchingAddresses(
// we’re declaring a lambda here; the [] signals the start
[] (const string& addr) { return addr.find( “.org” ) != string::npos; }
);
}
Lambda函数和STL
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
//…
for ( auto itr = v.begin(), end = v.end(); itr != end; itr++ )
{
cout << *itr;
}
#include<algorithm>
vector<int> v;
v.push_back( 1 );
v.push_back( 2 );
//…
for_each( v.begin(), v.end(), [] (int val)
{
cout << val;
} );