C++ Find_If Lambda

How to use lambda for std::find_if

Try this:

std::find_if(
myVector.begin(), myVector.end(),
[&toFind](const MyStruct& x) { return x.m_id == toFind.m_id;});

Alternatively, if you had defined an appropriate == overload for MyStruct, you could just use find:

std::find(myVector.begin(), myVector.end(), toFind);  // requires ==

The find_if version is usually best when you have some kind of heterogeneous lookup, for example if you were just given an int, not a value of MyStruct.

C++ lambda expression in std::find_if?

You've got your capture and argument reversed. The bit inside the [] is the capture; the bit inside () is the argument list. Here you want to capture the local variable i and take a as an argument:

[i](LWItem a)->bool { return a->GetID()==i; } 

This is effectively a shorthand for creating a functor class with local variable i:

struct {
LWItemID i;
auto operator()(LWItem a) -> bool { return a->GetID()==i; }
} lambda = {i};

C++ finding a value using find_if

Return value from find_if according to reference is

An iterator to the first element in the range for which pred does not return false.

pred is your lambda and it must return bool value.
If you want to use instruction in your lambda, you have to capture this variable

[instruction] (const pair<string,int>& p) { return  p.first == instruction; }

and the call of find_if when we know it returns iterator looks as follows

auto it = find_if ( begin(machine_opTable), end(machine_opTable), [instruction] (const pair<string,int>& p) { return  p.first == instruction; });
if (it != machine_opTable.end())
{
// access to found pair
}
else
; // pair not found

find_if with lambda and capturing variables

You simply have to take a std::pair (a move) as à parameter inside your lambda:

auto legalMoves = find_if(possible_moves.begin(),
possible_moves.end(),
[](std::pair<int, int> const& a_move)
{
int x, y;
std::tie(x, y) = a_move;
// do whatever you want
});

You could also use auto:

auto legalMoves = find_if(std::begin(possible_moves), std::end(possible_moves),
[](auto const& a_move) {
int x, y;
std::tie(x, y) = a_move;
// do whatever you want
});

Using find_if with a vector of pointers: How to pass pointer by const reference to lambda?

You want to have const reference to pointer, not reference to const pointer:

[](obj* const& instance) { if(instance->a == 5) return true; return false; }

or with type alias for obj pointer, it is much clearer:

using PtrObj = obj*;
std::find_if(begin(v), end(v), [](const PtrObj& instance) { if(instance->a == 5) return true; return false; });


Related Topics



Leave a reply



Submit