what happens when you modify an element of an 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 的元素时会发生什么?
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01