Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map<T, bool>, count values that are true

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?

like image 770
fuenfundachtzig Avatar asked Apr 15 '15 10:04

fuenfundachtzig


People also ask

How do you check if a value exists in a map in C++?

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

How do you count the values on a map?

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.

What does map return if key not found C++?

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().

What is STD count?

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.


2 Answers

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"
like image 73
Alex Shtof Avatar answered Sep 18 '22 08:09

Alex Shtof


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;
like image 36
Nim Avatar answered Sep 21 '22 08:09

Nim