I have a map:
std::map<std::string, bool> all_triggers_didfire;
I fill it and in the end would like to obtain the number of values that are true. The following code works:
int count_did_fire = std::count_if(
all_triggers_didfire.begin(),
all_triggers_didfire.end(),
[](std::pair<std::string, bool> p){return p.second;}
);
Is there an easier way than to define a lambda expression for this?
To check if a key exists in a C++ map, you can use std::map::count. It returns 0 (the key is absent) or 1 (the key is present).
map count() function in C++ STL Return Value: The function returns the number of times the key K is present in the map container. It returns 1 if the key is present in the container as the map only contains a unique key. It returns 0 if the key is not present in the map container.
Return Value: The function returns an iterator or a constant iterator which refers to the position where the key is present in the map. If the key is not present in the map container, it returns an iterator or a constant iterator which refers to map. end().
std::count() returns number of occurrences of an element in a given range. Returns the number of elements in the range [first,last) that compare equal to val.
I would use std::set instead of std::map. They are semantically equivalent but using std::set is easier. Example:
std::set<std::string> triggers_that_did_fire;
int count_did_fire = triggers_that_did_fire.size();
When you originally populate the triggers_that_did_fire
set, you can do the following:
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"
Sometimes, a simple for loop is a little clearer:
auto count = 0;
for (auto&& p : all_triggers_didfire)
if (p.second)
++count;
EDIT 1: I'll post the original code in case anyone cannot see the edit history..
auto count = 0;
for (auto& p : all_triggers_didfire)
count += p.second;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With