Using lambdas with the STL

From OPeNDAP Documentation
Revision as of 18:01, 24 November 2021 by Jimg (talk | contribs)
⧼opendap2-jumptonavigation⧽
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Using lambdas with the STL

Change code like:

 // Note that in order for this to work the second argument must not be a reference.
 // jhrg 8/20/13
 static bool
 name_eq(D4Group *g, const string name)
 {
	return g->name() == name;
 }

 groupsIter g = find_if(grp_begin(), grp_end(), bind2nd(ptr_fun(name_eq), grp_name));

to:

 auto g = find_if(grp_begin(), grp_end(), [grp_name](const D4Group *g) { return g->name() == grp_name; });
                                           ^         ^                                       ^
                                           1         2                                       3

Where [grp_name](const D4Group *g) { return g->name() == grp_name; } is a C++ Lambda function (anonymous function). This lambda function use uses a 'capture.' The square braces at #1 name the captured variable. Its value is taken from the current environment when the lambda is instantiated at runtime and used at #3 in the function. At #2 the argument to the lambda function is declared as a const pointer so the compiler knows the function won't be modifying the object. C++ STL functions like find_if() take predicates (which this lambda function is) and that can streamline code quite a bit.