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

前端 未结 4 1590
故里飘歌
故里飘歌 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 06:43

    For most purposes, a. and b. are the same. So the real question is, when to use a/b and when to use c.

    The answer is: use a or b if "less than" makes sense for your object in unequivocal terms. If your class is a number, use <.

    If "less than" makes no sense in the context of your class, then please don't overload "operator<" for your class. It will confuse users. Use c. instead, and either make it a nested class or typedef it inside your class so you can write it as Widget::Compare.

提交回复
热议问题