Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1843
  • Last Modified:

Using count_if with stl Map container class


I'm quite new to C++ and and could not find anything on the net via Google that can help me answer this question.

Suppose I have a map container declared as:  map<int, state>
where state is an enum of three possible values.  

I was wondering if I can use count_if to return the total number count for all pairs in the map where state = SOME_VALUE

Of course, I can create a trivial function to count this myself, but wanted to use a pre-existing algorithm from STL.


- Dan
1 Solution
Yes, you can do that.

You will have to pass count_if an iterator to the beginning of the map, an iterator to the end of the map, and a predicate.  You can get the iterators from the map's begin() and end() functions.

The predicate is more tricky.  count_if has to be able to call it like a function, with a map element as a parameter and a bool return value.  So if you only wanted to count the elements with some one value you could hard-code, you could just code that value in a function, like this:

bool predicate(const pair<int, state>& inputPair)
    return inputPair.second == SOME_VALUE;

With this definition, you would just pass "predicate" (without the quote marks) as the third parameter to count_if.

If you need the value checked to be variable at run-time, it's more complicated, but still possible.  You can pass a function object that has the value stored in it at run_time.  For example:

struct statePredicate
      //  The constructor saves the value to be checked.
      statePredicate(state inputState) : m_state(inputState) {}
      //  The operator() function lets an object of this class be called like a function.
      bool operator() (const pair<int, state>& pr)
            //  Report whether the map element has the value previously passed to the constructor.
            return pr.second == m_state;
      state m_state;

In this case, as the third parameter to count_if, you would pass a temporary statePredicate object constructed with the value you wanted counted.  For example:

size_type count = count_if(amap.begin(), amap.end(), statePredicate(SOME_VALUE));

dkf360Author Commented:
Thanks.  It was exactly what I needed to know.
And for your reference, take a look at this for the STL map :


and more specifically, for count_if :


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now