C++ std::set 如何处理元素的动态排序

标签 c++ set stdset

我有一个用我自己的 comp 函数声明的集合:

set<int, my_comp> my_set;

比较函数使用存储在别处的一些数据来决定哪个 int 更大。 如果所述数据发生变化,集合中元素的顺序也会发生变化。

set 是如何处理的? 如果我知道一个 int 的相对位置可能已经改变,我是否必须删除并重新插入它?

详细信息:特别是,my_comp 使用整数作为索引来访问 vector 并比较 vector 中包含的值。所述值必然会发生变化。

最佳答案

不,对于 std::set 中的元素,严格的弱顺序不得更改,键必须被视为 const

比较函数必须是strict weak ordering的模型:

A strict weak ordering has the following properties. For all x, y, and z in S,

  • For all x, it is not the case that x < x (irreflexivity).
  • For all x, y, if x < y then it is not the case that y < x (asymmetry).
  • For all x, y, and z, if x < y and y < z then x < z (transitivity).
  • For all x, y, and z, if x is incomparable with y, and y is incomparable with z, then x is incomparable with z (transitivity of incomparability).

更好的解决方案可能是排序的 std::vector,以及 std::sort(对其进行排序)、std::lower_bound(查找和插入元素),std::inplace_merge(插入元素)。

关于C++ std::set 如何处理元素的动态排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124732/

相关文章:

c# - 在 Windows 中全局检测双击

java - Set 引用变量中的 TreeSet 实例

c++ - std::set 具有相同键和不同比较器的迭代器

Python递归设置值排列字典

c++ - C++ 中 std::set 的自定义比较运算符和自定义类

c++ - 查找字符串是否包含字符串并处理附加数字

c++ - g++ 是否有标志可以使这些错误更易于阅读?

c++ - 将旧的 C++ 代码从 Solaris 移植到 Linux

c++ - 在 C++ 中将 begin() 和 end() 与集合一起使用

c++ - 基于std::set的无序选择实现最终会重复