简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM