如果键是一对,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/