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

假如想象 提交于 2020-05-09 05:57:46

问题


#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 

    vector<pair<int,int>>v;
    v.push_back(make_pair(1,3));
    v.push_back(make_pair(1,1));
    v.push_back(make_pair(2,19));
    v.push_back(make_pair(2,4));

    int n = 4; 

    stable_sort(v.begin(),v.end()); 

    for (int i = 0; i < n; i++) 
        cout << "[" << v[i].first << ", " << v[i].second 
             << "] "; 

    return 0; 
} 

Output : [1, 1] [1, 3] [2, 4] [2, 19] Expected Output : [1, 3] [1, 1] [2, 19] [2, 4]

Why does the vector of pairs not maintain the relative ordering even after applying stable sort, when we know that by default the vector of pairs is sorted on the basis of first element of the vector? If I write the comparator function, then it is working properly but not when I don't define any comparator function. Why is it so?


回答1:


The reference for operator< of std::pair<int, int> 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.




回答2:


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;
}


来源:https://stackoverflow.com/questions/61570740/stable-sort-on-a-vector-of-pairs-by-first-element-in-pair-in-increasing-order-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!