Difference between revisions of "Using lambdas with the STL"

From OPeNDAP Documentation
(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...")
 
m
Line 22: Line 22:
 
</pre>
 
</pre>
  
Where ''[grp_name](const D4Group *g) { return g->name() == grp_name; }'' is a C++ Lambda (anonymous function).
+
Where ''[grp_name](const D4Group *g) { return g->name() == grp_name; }'' is a C++ Lambda function (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.
+
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 is what this lambda function is) and that can streamline code quite a bit.

Revision as of 18:00, 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 is what this lambda function is) and that can streamline code quite a bit.