1

I have an unordered map with user-defined hash and equality functions.

I would like to count the number of times equality comparison function is called after adding all the elements to the map. Is there an easy way to do this?

1 Answer 1

2

In your custom equality function count them:

struct equality_comparer : std::binary_function<MyType, MyType, bool> {
    static int counter_;

    bool operator()( MyType const& lhs, MyType const& rhs ) {
        ++counter_;
        return lhs == rhs;
    }
};
int equality_comparer::counter_ = 0;

And then after insertion to the map complete: equality_comparer::counter_ = 0.

As mentioned by @PiotrNycz you can use this:

struct equality_comparer : std::binary_function<MyType, MyType, bool> {
    mutable int counter_;
  //^^^^^^^
    equality_comparer() : counter_(0) {}
    bool operator()( MyType const& lhs, MyType const& rhs ) {
        ++counter_;
        return lhs == rhs;
    }
    void reset_counter() {counter_ = 0;}
};

Then you can have myMap.key_eq().reset_counter() instead of equality_comparer::counter_ = 0 in previous code and myMap.key_eq().counter_ to access counter value.

Sign up to request clarification or add additional context in comments.

4 Comments

static is not needed. And it gives wrong result if OP uses more than one map. Results from non static counter can be get by: someMap.key_eq().counter
@PiotrNycz +1 You are certainly right about this, that was first thing that I think about it, and then I want to edit my answer but I think its already work for a test.
@BigBoos you can always add this as an alternative (or just better proposition) for next readers. The answers are read not only by OPs.
Thanks, but now I'm getting an error because bool operator() is no longer const. Is there a way around this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.