猿问

请问 使用自定义std :: set比较器

使用自定义std :: set比较器

我试图将一组整数中的项的默认顺序更改为lexicographic而不是numeric,并且我无法使用g ++进行以下编译:

file.cpp:

bool lex_compare(const int64_t &a, const int64_t &b) {
    stringstream s1,s2;
    s1 << a;
    s2 << b;
    return s1.str() < s2.str();}void foo(){
    set<int64_t, lex_compare> s;
    s.insert(1);
    ...}

我收到以下错误:

error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’error:   expected a type, got ‘lex_compare’

我究竟做错了什么?


慕桂英4014372
浏览 578回答 3
3回答

浮云间

您正在使用一个函数,因为您应该使用仿函数(一个重载()运算符的类,因此可以像函数一样调用它。struct&nbsp;lex_compare&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;bool&nbsp;operator()&nbsp;(const&nbsp;int64_t&&nbsp;lhs,&nbsp;const&nbsp;int64_t&&nbsp;rhs)&nbsp;const&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stringstream&nbsp;s1,&nbsp;s2; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s1&nbsp;<<&nbsp;lhs; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s2&nbsp;<<&nbsp;rhs; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;s1.str()&nbsp;<&nbsp;s2.str(); &nbsp;&nbsp;&nbsp;&nbsp;}};然后使用类名作为类型参数set<int64_t,&nbsp;lex_compare>&nbsp;s;如果你想避免仿函数样板代码,你也可以使用函数指针(假设lex_compare是一个函数)。set<int64_t,&nbsp;bool(*)(const&nbsp;int64_t&&nbsp;lhs,&nbsp;const&nbsp;int64_t&&nbsp;rhs)>&nbsp;s(&lex_compare);

幕布斯6054654

1.现代C ++ 11解决方案auto cmp = [](int a, int b) { return ... };std::set<int, decltype(cmp)> s(cmp);我们使用lambda函数作为比较器。像往常一样,比较器应该返回布尔值,指示作为第一个参数传递的元素是否被认为是在它定义的特定严格弱顺序中的第二个之前。在线演示2.与第一种解决方案类似,但功能代替lambda使比较器成为通常的布尔函数bool cmp(int a, int b) {     return ...;}然后使用它std::set<int, decltype(&cmp)> s(&cmp);在线演示3.使用struct with ()operator的旧解决方案struct cmp {     bool operator() (int a, int b) const {         return ...     }};// ...// laterstd::set<int, cmp> s;在线演示4.替代解决方案:从布尔函数创建struct采取布尔函数bool cmp(int a, int b) {     return ...;}并使用它来构建struct std::integral_constant#include <type_traits>using Cmp = std::integral_constant<decltype(&cmp), &cmp>;最后,使用struct作为比较器std::set<X, Cmp> set;在线演示

小怪兽爱吃肉

我编写了一个用于封装仿函数样板的适配器。template< class T, bool (*comp)( T const &, T const & ) >class set_funcomp {     struct ftor {         bool operator()( T const &l, T const &r )             { return comp( l, r ); }     };public:     typedef std::set< T, ftor > t;};// usagebool my_comparison( foo const &l, foo const &r );set_funcomp< foo, my_comparison >::t boo; // just the way you want it!哇,我觉得那值得一试!
随时随地看视频慕课网APP
我要回答