Using lambdas with the STL

From OPeNDAP Documentation
Revision as of 17:59, 24 November 2021 by Jimg (talk | contribs) (Created page with "= Using lambdas with the STL = Change code like: <pre> // Note that in order for this to work the second argument must not be a reference. // jhrg 8/20/13 static bool na...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
⧼opendap2-jumptonavigation⧽

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 (anonymous function). This 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 is what this lambda function is) and that can streamline code quite a bit.