stable_sort on a vector of pairs by first element in pair in increasing order without comparator function in C++

前端 未结 2 1793
情深已故
情深已故 2021-01-22 14:16
#include  
using namespace std; 

int main() 
{ 

    vector>v;
    v.push_back(ma         


        
2条回答
  •  暖寄归人
    2021-01-22 14:48

    The comparator used uses both values in the pairs when doing the comparison.

    It compares lhs and rhs lexicographically by operator< (operator<=> since C++20), that is, compares the first elements and only if they are equivalent, compares the second elements.

    If I write the comparator function, then it is working properly

    That's because you've probably implemented it like this:

    [](const auto& lhs, const auto& rhs) {
        return lhs.first < rhs.first;
    }
    

    The default comparator does something equivalent to this:

    [](const auto& lhs, const auto& rhs) {
        return lhs.first == rhs.first ? lhs.second < rhs.second : lhs.first < rhs.first;
    }
    

提交回复
热议问题