如何根据对的第二个元素在STL c ++中对对的集合排序?

时间:2019-12-29 13:40:07

标签: c++ sorting stl set

假设我已经创建

set<pair<int,int>> s

我希望它根据对的第二个元素自动排序。该怎么做?我在网上搜索,但未找到任何解决方案。 我们可以为此提供一些外部功能吗? 谢谢

1 个答案:

答案 0 :(得分:1)

std::set与自定义比较函子一起使用:

using pair_type = std::pair<int, int>;
struct PairCmp
{
    bool operator()(const pair_type& lhs, const pair_type& rhs) const
    { 
        return lhs.second < rhs.second; 
    }
};
std::set<pair_type, PairCmp> s;