Reputation: 11
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?
Upvotes: 1
Views: 126
Reputation: 6914
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.
Upvotes: 2