Search code examples
c++setfunctor

How does comparator in a set works with functor in C++?


Here is a simple program to show my point:

#include <iostream>
#include <set>
class comparator
{
public:
  bool operator()(int* a, int* b){return *a < *b;}
};
int main()
{
  std::set<int*> v1{new int{1}, new int{1}, new int{2}, new int{2}};
  std::set<int*, comparator> v2{new int{1}, new int{1}, new int{2}, new int{2}};
  std::cout << v1.size() << std::endl; // 4
  std::cout << v2.size() << std::endl; // 2
  return 0;
}

Before using functor, the set removes duplicate elements by address of integers. However, after including functor, it removes based on the values. The problem is that in the functor I didn't define the operator to return true on duplicate values, so why would it show this behavior?


Solution

  • I didn't define the operator to return true on duplicate values, so why would it show this behavior?

    Because a std::set is intended to work with "less than" comparator, and it is implemented that way. That is, if for two values x and y in the set both x<y and y<x are false, then x and y are assumed to be equal and thus they are duplicates.