简体   繁体   中英

check map keys are in set using std::equal or std::all_of

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 :)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM