对对向量上的stable_sort由对中的第一个元素按升序排列,没有C ++中的比较器功能 [英] stable_sort on a vector of pairs by first element in pair in increasing order without comparator function in C++

查看:116
本文介绍了对对向量上的stable_sort由对中的第一个元素按升序排列,没有C ++中的比较器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

输出: [1,1] [1, 3] [2,4] [2,19]
预期输出: [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?

推荐答案

引用,用于 std :: pair< int,int> 操作符< c>表示

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


按运算符在字典上比较lhs和rhs <,即比较第一个元素,并且仅当它们相等时,比较第二个元素。

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

因此,两个元素都用于比较 std :: pair ,您看到的是一个完全排序的向量。元素的相对顺序仅在两个或更多元素可以视为相等时才有意义。由于该对的两个值都用于比较,因此不能认为它们相等。因此,相对顺序在这里不相关。

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

将看到输出

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

这里前两对和最后两对被认为是相等的,并保持它们的相对顺序。

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

这篇关于对对向量上的stable_sort由对中的第一个元素按升序排列,没有C ++中的比较器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆