当你修改std :: set的元素时会发生什么? [英] what happens when you modify an element of an std::set?

查看:122
本文介绍了当你修改std :: set的元素时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我通过迭代器更改std :: set的一个元素,我知道它不是重新插入或分离的,但是有没有提到它是否触发未定义的行为?例如,我想象插入会拧。

If I change an element of an std::set, for example, through an iterator, I know it is not "reinserted" or "resorted", but is there any mention of if it triggers undefined behavior? For example, I would imagine insertions would screw up. Is there any mention of specifically what happens?

推荐答案

你不应该直接编辑存储在集合中的值。我从MSDN文档中复制这个有些权威的文档:

You should not edit the values stored in the set directly. I copied this from MSDN documentation which is somewhat authoritative:


STL容器类集用于
用于存储和检索数据
来自一个集合,其中所包含的元素的值
是唯一的
并且作为根据
的键值,数据自动地被
排序。
集合中的元素的值不能直接更改。
相反,您必须删除旧值
并插入具有新值的元素。

The STL container class set is used for the storage and retrieval of data from a collection in which the values of the elements contained are unique and serve as the key values according to which the data is automatically ordered. The value of an element in a set may not be changed directly. Instead, you must delete old values and insert elements with new values.

容易明白。 set 实现将无法知道您已修改其背后的值。正常的实现是一个红黑树。更改值后,该实例的树中的位置将是错误的。你会期望看到所有方式的错误行为,例如 exists 查询返回错误的结果,因为搜索沿着树的错误分支。

Why this is is pretty easy to understand. The set implementation will have no way of knowing you have modified the value behind its back. The normal implementation is a red-black tree. Having changed the value, the position in the tree for that instance will be wrong. You would expect to see all manner of wrong behaviour, such as exists queries returning the wrong result on account of the search going down the wrong branch of the tree.

这篇关于当你修改std :: set的元素时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆