fue*_*zig 14 c++ lambda dictionary countif
我有一张地图:
std::map<std::string, bool> all_triggers_didfire;
Run Code Online (Sandbox Code Playgroud)
我填写它,最后想获得真实值的数量.以下代码有效:
int count_did_fire = std::count_if(
all_triggers_didfire.begin(),
all_triggers_didfire.end(),
[](std::pair<std::string, bool> p){return p.second;}
);
Run Code Online (Sandbox Code Playgroud)
有没有比为此定义lambda表达式更简单的方法?
Ale*_*tof 12
我会使用std :: set而不是std :: map.它们在语义上是等价的,但使用std :: set更容易.例:
std::set<std::string> triggers_that_did_fire;
int count_did_fire = triggers_that_did_fire.size();
Run Code Online (Sandbox Code Playgroud)
最初填充triggers_that_did_fire集合时,可以执行以下操作:
triggers_that_did_fire.insert(mystring); //equivalent to setting to "true" in your map
triggers_that_did_fire.remove(mystring); //equivalent to setting to "false"
Run Code Online (Sandbox Code Playgroud)
有时,一个简单的for循环更清晰:
auto count = 0;
for (auto&& p : all_triggers_didfire)
if (p.second)
++count;
Run Code Online (Sandbox Code Playgroud)
编辑1:我会发布原始代码,万一有人看不到编辑历史..
auto count = 0;
for (auto& p : all_triggers_didfire)
count += p.second;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2932 次 |
| 最近记录: |