【问题标题】:How to sort set of pairs in STL c++ according to second element of pair?如何根据对的第二个元素对 STL c++ 中的对集进行排序?
【发布时间】:2019-12-29 13:40:07
【问题描述】:

假设我已经创建了

set<pair<int,int>> s

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

【问题讨论】:

  • 如果那是你创建的集合,它已经在第一、第二的领带上“排序”了。如果您希望从一开始就不同排序,请为std::set 的比较器参数提供自定义比较类型(请参阅第二个模板参数)。或者,您可以在实例化时提供一个比较器实例覆盖(参见std::set::set 的选项#1 和#2。
  • 我很想以stackoverflow.com/questions/2620862/…的骗子身份关闭

标签: c++ sorting stl set


【解决方案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;

【讨论】:

  • Effective STL 由 Scott Meyers 撰写。有点过时的 c++11 明智,但要花很多钱来理解 STL 库的工作原理(这是完全最新的)。
猜你喜欢
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 2011-05-21
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多