使用STL c++对向量进行排序

Sort vector pair using STL C++

本文关键字:排序 向量 STL c++ 使用      更新时间:2023-10-16

我想根据first的值按降序对向量对排序。如果第一个的值相同,我想根据第二个的值按升序排序。在STL中有一些方法可以做到这一点吗?假设这是向量对

(3,u)
(1,d)
(3,t)

如果我使用这个-

vector < pair <int ,char > >M1(3);
sort(M1.rbegin(),M1.rend());

这给了我-

(3,u)
(3,t)
(1,d)

但这就是我想要的-

(3,t)
(3,u)
(1,d)

是的,您所需要做的就是为std::pair提供一个比较器(或覆盖operator<)。

的例子:

template<typename T, typename U>
bool customComparison(const std::pair<T, U> &p1, const std::pair<T, U> &p2)
{
    return std::tie(p2.first, p1.second) < std::tie(p1.first, p2.second);
}
sort(vec.begin(), vec.end(), customComparison<int,char>);