Ordered sort in STL containers

前端 未结 1 931
北荒
北荒 2020-12-20 05:40

Sorry if the question title terminology is wrong, but here is what I want to do.I need to sort a vector of objects, but contrary to a typical comparison \"less than\" appro

相关标签:
1条回答
  • 2020-12-20 05:46

    std::sort has a third parameter which can be used to pass a boolean predicate that acts as custom comparator. Write your own comparator acording to your specifications and use it.

    For example:

    struct foo
    {
        std::string id;
    
        foo(const std::string& _id) : id( _id ) {}
    };
    
    //Functor to compare foo instances:
    struct foo_comparator
    {
        operator bool(const foo& lhs , const foo& rhs) const
        {
            return lhs.id < rhs.id;
        }
    };
    
    int main()
    {
        std::vector<foo> v;
    
        std::sort( std::begin(v) , std::end(v) , foo_comparator );
    }
    

    Also, in C++11 you could use a lambda:

    std::sort( std::begin(v) , std::end(v) , [](const foo& lhs , const foo& rhs) { return lhs.id < rhs.id; } );
    

    Finally, you can also overload the comparison operators (operator> and operator<) and use comparators provided by the standard library like std::greater:

    struct foo
    {
        std::string id;
    
        foo(const std::string& _id) : id( _id ) {}
    
        friend bool operator<(const foo& lhs , const foo& rhs)
        {
            return lhs.id < rhs.id;
        }
    
        friend bool operator>(const foo& lhs , const foo& rhs)
        {
            return rhs < lhs;
        }
    
        friend bool operator>=(const foo& lhs , const foo& rhs)
        {
            return !(lhs < rhs);
        }
    
        friend bool operator<=(const foo& lhs , const foo& rhs)
        {
            return !(lhs > rhs);
        }
    };
    
    
    int main()
    {
        std::vector<foo> v;
    
        std::sort( std::begin(v) , std::end(v) , std::greater );
    }
    
    0 讨论(0)
提交回复
热议问题