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

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

int main() 
{ 

    vector>v;
    v.push_back(ma         


        
2条回答
  •  粉色の甜心
    2021-01-22 15:03

    The reference for operator< of std::pair says that it

    Compares lhs and rhs lexicographically by operator<, that is, compares the first elements and only if they are equivalent, compares the second elements.

    So both elements are used to compare a std::pairand what you see is a fully sorted vector. Relative order of elements would only be relevant when two or more elements can be considered equal. Since both values of the pairs are used for comparison none of them can be considered equal. Thus relative order is not relevant here.

    You can use a custom comparator to only compare the first element:

    stable_sort(v.begin(), v.end(), [](const auto& a, const auto& b) {return a.first < b.first; });
    

    An will see the output

    [1, 3] [1, 1] [2, 19] [2, 4]
    

    Here the first two and last two pairs are considered equal and keep their relative order.

提交回复
热议问题