使用STL C ++对矢量对进行排序

时间:2015-08-05 03:25:50

标签: c++

我想基于first的值按照降序对矢量对进行排序。如果first的值相同,我想根据second的值按升序排序。在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)

1 个答案:

答案 0 :(得分:2)

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

示例:

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>);
相关问题