C++设置以对为键的排序

标签 c++ sorting set std-pair

如果键是一对,C++ 中的有序集合容器将如何对其键进行排序? (默认情况下没有自定义比较器)

假设我有一个键 (1,2) 和另一个键 (1,1)。

我说它会尝试根据对中的第一个值进行排序然后如果它们相等则继续比较第二对值是否正确?

所以在这种情况下 (1,1) 将在 (1,2) 之前。

最佳答案

模板类std::pair已经定义了operator < .因此,您可以对包含 std::pair 类型对象的容器进行排序.

来自 C++ 标准(20.3.3 专用算法)

template <class T1, class T2>
constexpr bool operator<(const pair<T1, T2>& x, const pair<T1, T2>& y);

2 Returns: x.first < y.first || (!(y.first < x.first) && x.second < y.second).

您还可以将两个对象视为 std::pair 类型对象的成员使用函数 std::tie .

这是一个演示程序

#include <iostream>
#include <utility>
#include <functional>
#include <algorithm>
#include <iterator>

int main() 
{
    std::pair<int, int> a[] = { { 1, 2 }, { 1, 1 } };

    for ( const auto &p : a ) 
    {
        std::cout << "< " << p.first << ", " << p.second << "> ";
    }
    std::cout << std::endl;

    std::sort( std::begin( a ), std::end( a ) );

    for ( const auto &p : a ) 
    {
        std::cout << "< " << p.first << ", " << p.second << "> ";
    }
    std::cout << std::endl;

    std::cout << std::endl;

    struct Pair
    {
        int x;
        int y;
    } b[] = { { 1, 2 }, { 1, 1 } };

    for ( const auto &p : b ) 
    {
        std::cout << "< " << p.x << ", " << p.y << "> ";
    }
    std::cout << std::endl;

    std::sort( std::begin( b ), std::end( b ), 
        []( const Pair &left, const Pair &right)
        {
            return std::tie( left.x, left.y ) < std::tie( right.x, right.y );
        } );

    for ( const auto &p : b ) 
    {
        std::cout << "< " << p.x << ", " << p.y << "> ";
    }
    std::cout << std::endl;

    return 0;
}

它的输出是

< 1, 2> < 1, 1> 
< 1, 1> < 1, 2> 

< 1, 2> < 1, 1> 
< 1, 1> < 1, 2> 

关于C++设置以对为键的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694784/

相关文章:

c++ - Windows 8/RT C++ 中的平台::字符串函数

java - 首先按薪水对员工对象列表进行排序,如果薪水相等,则按姓名排序

angular - Typescript - 如何在 map 中设置对象键的值

Python Pandas 根据另一个集合(集合)的成员资格选择行

c++ - XML<->SQLite 数据转换 C++ Linux

c++ - Box2d 销毁集合中的所有对象

python - Python 中通过其他数组排序索引对数组进行排序

postgresql - Postgres 函数 : how to return the first full set of data that occurs after specified date/time

c++ - 从 std::call_once 抛出异常

java - 如何用Java编写位排序程序?