修改 std::set 的元素时会发生什么?

what happens when you modify an element of an std::set?(修改 std::set 的元素时会发生什么?)

本文介绍了修改 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 容器类集用于存储和检索数据来自一个集合,其中的值包含的元素是独一无二的并作为关键值根据数据自动传送到的位置订购.a中元素的值set 不能直接更改.相反,您必须删除旧值并插入具有新值的元素.

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 的元素时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:修改 std::set 的元素时会发生什么?

基础教程推荐