c++ custom compare function for std::sort()

前端 未结 3 901
滥情空心
滥情空心 2020-12-01 10:42

I want to create custom compare function for std::sort(), to sort some key-value pairs std::pair

Here is my function

 template 

        
相关标签:
3条回答
  • 2020-12-01 11:02

    std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

    Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

    std::vector<pair<K,V>> items; 
    std::sort(items.begin(), items.end()); 
    

    If you really need to provide your own comparison function, then you need something along the lines of

    template <typename K, typename V>
    bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
    {
      return lhs.first < rhs.first;
    }
    
    0 讨论(0)
  • 2020-12-01 11:03

    Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

    It says:

    template< class RandomIt, class Compare >
    void sort( RandomIt first, RandomIt last, Compare comp );
    
    • comp - comparison function which returns ​true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

    Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

    std::sort(std::begin(container), std::end(container),
              [] (const auto& lhs, const auto& rhs) {
        return lhs.first < rhs.first;
    });
    
    0 讨论(0)
  • 2020-12-01 11:05

    Your comparison function is not even wrong.

    Its arguments should be the type stored in the range, i.e. std::pair<K,V>, not const void*.

    It should return bool not a positive or negative value. Both (bool)1 and (bool)-1 are true so your function says every object is ordered before every other object, which is clearly impossible.

    You need to model the less-than operator, not strcmp or memcmp style comparisons.

    See StrictWeakOrdering which describes the properties the function must meet.

    0 讨论(0)
提交回复
热议问题