How to create a std::set with custom comparator in C++?(如何在 C++ 中使用自定义比较器创建 std::set?)
问题描述
如何创建一组对,其中的元素(对)使用自定义 bool 函数进行排序?我写
How do I create a set of pairs, the elements of which (the pairs) are sorted with a custom bool function? I write
并得到错误:参数 2 的类型/值不匹配,需要一个类型,得到比较"
and get error : Type/value mismatch at argument 2, expected a type, got "compare"
我将比较"定义为
当然
推荐答案
方法一:使用函子
编写一个重载operator()
的类,这样它就可以像函数一样被调用:
Method 1: use functor
Write a class that overloads the operator()
so it can be called like a function:
然后,你可以使用类名作为类型参数
Then, you can use the class name as the type parameter
方法二:使用函数指针
假设 compare
是你要使用的函数:
这篇关于如何在 C++ 中使用自定义比较器创建 std::set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!