在 C++ 中,迭代器失效规则是否也适用于所有标准容器的指针?
In C++, do iterator invalidation rules also apply to pointers for all the std containers?
我有一些元素的容器 C。在我的算法中,这些元素需要分成两个子组 C1 和 C2,它们将在其中排序。现在,为了避免两次存储相同的数据,这两个子组可以是
- std::sets of pointers 指向容器 C 或
中的元素
- std::sets of iterators 指向容器中的元素 C.
我知道在遵循 Invalidation rules 时它会很好地与迭代器一起工作,但是我只会使用 C1 和 C2 设置取消引用实际值并将 pointer/iterator 从 C1 移动到 C2 或者反过来,没有别的。
从概念上讲,使用指针对我来说更有意义,但我不确定两件事:
使用指针实际上可以为某些标准容器节省一些内存吗?(因为迭代器是指针的泛化)
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。在我的算法中,这些元素需要分成两个子组 C1 和 C2,它们将在其中排序。现在,为了避免两次存储相同的数据,这两个子组可以是
- std::sets of pointers 指向容器 C 或 中的元素
- std::sets of iterators 指向容器中的元素 C.
我知道在遵循 Invalidation rules 时它会很好地与迭代器一起工作,但是我只会使用 C1 和 C2 设置取消引用实际值并将 pointer/iterator 从 C1 移动到 C2 或者反过来,没有别的。
从概念上讲,使用指针对我来说更有意义,但我不确定两件事:
使用指针实际上可以为某些标准容器节省一些内存吗?(因为迭代器是指针的泛化)
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}
插入的情况。