【问题标题】:is there a way to use set with online comparator? [closed]有没有办法将 set 与在线比较器一起使用? [关闭]
【发布时间】:2021-03-25 16:58:16
【问题描述】:

我想使用带有比较器 lambda 函数的 set 或 multiset 制作 RedBlackTree,并且该函数使用数组(为简单起见全局) 程序运行时数组正在改变

#include <iostream>
#include <set>
using namespace std;
int v[10];
auto x = [](pair<int, int> p1, pair<int, int> p2) { return p1.second+v[p1.first] <   p2.second+v[p2.first]; };
set<pair<int, int>, decltype(x)> s(x);
// i tested multiset with same answer
int main()
{
    s.insert({3, 2});
    s.insert({4, 1});
    s.insert({2, 10});
    s.insert({8, 8});
    v[2]=-100;
    for (auto x : s)
        cout << x.first<<":"<<x.second << endl;
}

预期:

2:10
4:1
3:2
8:8

但我明白了:

4:1
3:2
8:8
2:10

【问题讨论】:

  • 我认为这行不通。当set 中已有元素时,您无法动态更改排序(在这种情况下通过一些全局)。它不会重新排列容器。您只是使以前用于对元素排序的不变量无效。这看起来像是破坏数据结构的秘诀。

标签: c++ set comparator


【解决方案1】:

程序运行时数组正在改变

你不能有一个比较器函数来改变它的行为。

在您的示例中,set 是在 v[2]=-100; 分配之前构造的,并且在您进行分配之后它恰好保持其顺序,但这不是保证行为。

顺便说一句,#include &lt;bits/stdc++.h&gt; 是非标准的,会让你在这个网站上被否决。

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2018-03-15
    • 2016-11-01
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多