【问题标题】:How to define compare function for an array of sets?如何为一组集合定义比较函数?
【发布时间】:2020-05-11 12:11:14
【问题描述】:

我们在这里对单组有很好的解释:

但我想知道这对于如下集合的数组是如何工作的:

bool cmp(const pair <int, int> &a, const pair <int, int> &b) {
    if (b.first < a.first)
        return true;
    return a < b;
}

set <pair <int, int>, decltype(&cmp)> block[SQ](&cmp);

我更喜欢方法3,但你可以回答任何你喜欢的方法。

【问题讨论】:

  • 这是未定义的行为。比较函数不是严格的弱序。
  • set &lt;pair &lt;int, int&gt;, decltype(&amp;cmp)&gt; block[SQ](&amp;cmp) 无效。我猜你的意思是为每个数组元素调用set 的构造函数,比如set &lt;pair &lt;int, int&gt;, decltype(&amp;cmp)&gt; block[SQ] = { set &lt;pair &lt;int, int&gt;, decltype(&amp;cmp)&gt;(&amp;cmp), set &lt;pair &lt;int, int&gt;, decltype(&amp;cmp)&gt;(&amp;cmp), etc. }
  • 是的,我是这个意思;但是我该如何编码呢?​​

标签: c++ arrays set compare


【解决方案1】:

大概是这样的:

struct CmpWrapper {
  bool operator()(const pair <int, int> &a, const pair <int, int> &b) const {
    return cmp(a, b);
  }
};

set <pair <int, int>, CmpWrapper> block[SQ];

正如@SamVarshavchik 在 cmets 中指出的那样,cmp 不满足严格的弱排序要求(例如,存在对 pq,其中 cmp(p, q)cmp(q, p) 都是正确的)。直接或通过此包装器将其与 std::set 一起使用会表现出未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-13
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    相关资源
    最近更新 更多