简体   繁体   English

使用std :: equal或std :: all_of检查映射键是否已设置

[英]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. 我是C ++和谓语的新手,但遇到了问题。 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. 我试图检查unordered_map中的所有键是否存在于一个set或者甚至存在于另一个具有不同值类型的映射中的键。 Essentially, [key in set_ for key in map_.keys()] OR [key in map2_ for key in map1_.keys()] in python. 本质上, [key in set_ for key in map_.keys()] [key in map2_ for key in map1_.keys()] [key in set_ for key in map_.keys()][key in map2_ for key in map1_.keys()]

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. 但是我想使用std::all_ofstd::equal实现相同的目的。 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(...)... 编译器抱怨set_超出范围, 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. 默认情况下,Lambda无法访问在其作用域中声明的变量。 In order to access your set_ variable from the lambda function, you should capture it in the lambda function. 为了从lambda函数访问set_变量,应在lambda函数中捕获它。

The capture list is defined between the [] characters at the beginning of the lambda function. 捕获列表是在lambda函数开头的[]字符之间定义的。

In this case, I would use [&] which captures all objects from the scope by reference, including your set_ variable. 在这种情况下,我将使用[&]通过引用从作用域中捕获所有对象,包括set_变量。

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. 您应该阅读cppreference上的Lambda表达式页面以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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