Using lambdas with the STL: Difference between revisions

From OPeNDAP Documentation
⧼opendap2-jumptonavigation⧽
mNo edit summary
mNo edit summary
Line 25: Line 25:
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.
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.
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.
C++ STL functions like ''find_if()'' take predicates (which this lambda function is) and that can streamline code quite a bit.

Revision as of 18:01, 24 November 2021

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.