Sort a std::list with myclass::operator<(myclass &other)

后端 未结 5 592
一生所求
一生所求 2021-01-12 04:31

I have a std::list and in my class I have myclass::operator<(myclass &other) defined.

I use the std::list.sort

5条回答
  •  -上瘾入骨i
    2021-01-12 05:36

    It'll sort the pointer as std::sort( Container ) use the operator< defined T. Here T is myclass*, then it is sorted using comparison over pointer.

    You can pass a custom comparator functor to std::sort so make one take takes two myclass* and return the proper comparison :

    template
    struct ptr_comparison
    {
       bool operator()(T* a, T* b) { return *a < *b; } 
    };
    
    list mylist;
    
    // later
    
    mylist.sort(ptr_comparison());
    

提交回复
热议问题