Using custom std::set comparator

后端 未结 5 1561
耶瑟儿~
耶瑟儿~ 2020-11-22 16:03

I am trying to change the default order of the items in a set of integers to be lexicographic instead of numeric, and I can\'t get the following to compile with g++:

5条回答
  •  借酒劲吻你
    2020-11-22 17:01

    You are using a function where as you should use a functor (a class that overloads the () operator so it can be called like a function).

    struct lex_compare {
        bool operator() (const int64_t& lhs, const int64_t& rhs) const {
            stringstream s1, s2;
            s1 << lhs;
            s2 << rhs;
            return s1.str() < s2.str();
        }
    };
    

    You then use the class name as the type parameter

    set s;
    

    If you want to avoid the functor boilerplate code you can also use a function pointer (assuming lex_compare is a function).

    set s(&lex_compare);
    

提交回复
热议问题