Using custom std::set comparator

后端 未结 5 1553
耶瑟儿~
耶瑟儿~ 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 16:59

    std::less<> when using custom classes with operator<

    If you are dealing with a set of your custom class that has operator< defined, then you can just use std::less<>.

    As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find APIs:

    template< class K > iterator find( const K& x );
    template< class K > const_iterator find( const K& x ) const;
    

    which allow you to do:

    main.cpp

    #include 
    #include 
    
    class Point {
        public:
            // Note that there is _no_ conversion constructor,
            // everything is done at the template level without
            // intermediate object creation.
            //Point(int x) : x(x) {}
            Point(int x, int y) : x(x), y(y) {}
            int x;
            int y;
    };
    bool operator<(const Point& c, int x) { return c.x < x; }
    bool operator<(int x, const Point& c) { return x < c.x; }
    bool operator<(const Point& c, const Point& d) {
        return c.x < d;
    }
    
    int main() {
        std::set> s;
        s.insert(Point(1, -1));
        s.insert(Point(2, -2));
        s.insert(Point(0,  0));
        s.insert(Point(3, -3));
        assert(s.find(0)->y ==  0);
        assert(s.find(1)->y == -1);
        assert(s.find(2)->y == -2);
        assert(s.find(3)->y == -3);
        // Ignore 1234, find 1.
        assert(s.find(Point(1, 1234))->y == -1);
    }
    

    Compile and run:

    g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
    ./main.out
    

    More info about std::less<> can be found at: What are transparent comparators?

    Tested on Ubuntu 16.10, g++ 6.2.0.

提交回复
热议问题