operator< comparing multiple fields

前端 未结 6 858
北海茫月
北海茫月 2020-11-28 13:03

I have the following operator< that is supposed to sort first by a value, then by another value:

    inline bool operator < (const obj& a, const ob         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 13:27

    Think of what happens if a.field1 is greater than b.field1 but a.field2 is less than b.field2. In that circumstance, you compare based solely on field2 which is not what you want.

    You only want to bring field2 into play where the field1 fields are equal, so what you're looking for is something like (pseudo-code):

    if a.field1 < b.field1: return true
    if a.field1 > b.field1: return false
    # field1s is equal here.
    return a.field2 < b.field2
    

提交回复
热议问题