gpt4 book ai didi

c++ - 是否可以从 std::set 中删除修改后的元素?

转载 作者:行者123 更新时间:2023-11-28 06:10:17 24 4
gpt4 key购买 nike

我需要一个可以修改元素的排序集合。修改后删除元素是否安全?可以修改排序键。

auto it=s.find(e)
modify(e)
s.erase(it)

我已经在 VS2010 中进行了一些测试,并且成功了。我认为 erase(it) 不需要搜索元素,因此不需要在被删除的元素上调用比较。

很难修改整个程序以在修改前删除元素,这就是我寻找替代解决方案的原因。

编辑:添加工作示例以使其更清晰

#include <iostream>
#include <algorithm>
#include <set>

template <typename T>
struct PtrCmp
{
bool operator()(const T* x, const T* y) const
{
return *x<*y;
}
};

int main()
{
std::set<int*, PtrCmp<int>> aset;
int t[]={1,2,3,4};
for(int i=0;i<4;++i)
aset.insert(&t[i]);

auto it=aset.find(&t[2]);
t[2]=5;
aset.erase(it);

for(auto it=aset.begin(); it!=aset.end(); ++it)
std::cout<<**it<<std::endl;
}

最佳答案

在您的示例中,t[2]=5; 修改了比较器中使用的值,例如用于重新平衡 set 容器后面的树数据结构。因此,这种修改是不安全的,因为平衡树算法可能会在节点上的事实键发生更改时失败,因此与该树节点的期望不匹配。 erase 操作可能会触发树重新平衡,这就是您获得未定义行为的方式。因此,通过修改比较器中使用的值,您实际上破坏了 set 容器后面的树的平衡。

关于c++ - 是否可以从 std::set 中删除修改后的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31400748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com