Defining < for STL sort algorithm - operator overload, functor or standalone function?

前端 未结 4 1698
故里飘歌
故里飘歌 2021-01-02 06:05

I have a stl::list containing Widget class objects. They need to be sorted according to two members in the Widget class.

For the sorting to work, a less-than compara

4条回答
  •  清歌不尽
    2021-01-02 07:00

    They should all be the same in terms of performance, but there are other differences between them:

    • The first two save you having to explicitly specify the comparator, and can be used easily with other operations, possibly poorly defined ones that don't allow explicit specification of a comparator.

    • Only the functor allows additional data for the comparison. For example, if you were comparing ints, you could create a comparison that compares their distance from a third point, P, which would be a member of the functor instance.

    • Functors are generally less easy to read (to those not familiar with C++).

    Note, you don't need to inherit binary_operator for it to work, although it does give you some nice typedefs.

提交回复
热议问题