Reputation: 93
I'm new to C++ and predicates but I'm running into a problem. I'm trying to check if all keys in an unordered_map
exist in a set
or even keys in another map with different value type for that matter.
Essentially, [key in set_ for key in map_.keys()]
OR [key in map2_ for key in map1_.keys()]
in python.
one approach is the following:
for( auto itr = map_.begin(); itr != map_.end(); ++itr ) {
if( set_.find( itr->first ) == set_.end() ) return false;
}
But I want to use std::all_of
or std::equal
to achieve the same. Here's what I have so far:
some_function() {
//set_ and map_ in scope
areEqual = std::equal( map_.begin(), map_.end(), set_,
[]( auto itr ){ return set_.find( itr->first ) != set_.end(); } );
}
compiler complains that set_
is out of scope in return set_.find(...)...
I also tried
class checker {
public:
bool operator()( map_itr itr )
{ return set_.find( itr->first ) != set_.end(); }
};
but ran into the same problem.
Any help or pointers is greatly appreciated :)
Upvotes: 0
Views: 372
Reputation: 1914
Lambdas can't access variables declared in its scope by default. In order to access your set_
variable from the lambda function, you should capture it in the lambda function.
The capture list is defined between the []
characters at the beginning of the lambda function.
In this case, I would use [&]
which captures all objects from the scope by reference, including your set_
variable.
some_function() {
areEqual = std::equal( map_.begin(), map_.end(), set_,
[&]( auto itr ){ return set_.find( itr->first ) != set_.end(); } );
}
You should read the Lambda expressions page on cppreference for further information.
Upvotes: 1