gpt4 book ai didi

c++ - 在 C++ 中,迭代器失效规则是否也适用于所有标准容器的指针?

转载 作者:行者123 更新时间:2023-11-28 05:24:30 31 4
gpt4 key购买 nike

我有一些元素的容器C。在我的算法中,这些元素需要分成两个子组 C1C2,它们将在其中排序。现在,为了避免两次存储相同的数据,这两个子组可以是

  1. std::sets of pointers 指向容器 C 中的元素,或
  2. std::sets of iterators 指向容器 C 中的元素。

我知道在遵循 Invalidation rules 时它会很好地与迭代器一起工作,但是我只会使用 C1C2 集来取消引用实际值并移动指针/迭代器C1C2 或相反,没有别的。

从概念上讲,使用指针对我来说更有意义,但我不确定两件事:

使用指针真的可以为某些标准容器节省一些内存吗?(因为迭代器是指针的泛化)

执行 Invalidation rules还为所有 std 容器申请原始指针?

最佳答案

Could the use of pointers actually save some memory for some std containers?

从我的角度来看,我认为指针的成本总是小于或等于迭代器。当你使用指针时,它会花费你一个指针。虽然迭代器实现因实现而异,但它必须有一些方法来引用原始容器,这将花费你一个指针或一个引用,在最好的情况下,这将花费你与一个指针一样多。和 this test似乎支持我。

Do the Invalidation rules also apply for raw pointers for all std containers?

来自 C++ FAQ :

Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object.

然后对这些容器进行的任何操作都不会使 your linked question 中的引用无效即使该操作使迭代器无效,也不会使指针无效,这是 unordered_[multi]{set,map} 插入的情况。

关于c++ - 在 C++ 中,迭代器失效规则是否也适用于所有标准容器的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40829367/

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