簡體   English   中英

集合中的比較器如何與 C++ 中的函子一起使用?

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

這是一個簡單的程序來說明我的觀點:

#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;
}

在使用仿函數之前,該集合通過整數地址刪除重復元素。 但是,在包含仿函數后,它會根據值刪除。 問題是在仿函數中我沒有定義運算符在重復值上返回true ,那么它為什么會顯示這種行為呢?

我沒有定義運算符在重復值上返回 true,那么它為什么會顯示這種行為呢?

因為std::set旨在與“小於”比較器一起使用,並且以這種方式實現。 也就是說,如果對於集合中的兩個值xyx<yy<x都為假,則假定xy相等,因此它們是重復的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM