BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #39545同步于 2010/5/24
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

什么是迭代器、指针和引用的失效?

Cedronella
2010/5/24镜像同步4 回复
看书时看到下面一段话: Do you need to minimize iterator, pointer, and reference invalidation? If so, you'll want to use node-based containers, because insertions and erasures on such containers never invalidate iterators, pointers, or references (unless they point to an element you are erasing). In general, insertions or erasures on contiguous-memory containers may invalidate all iterators, pointers, and ref-erences into the container. 中文翻译: 你要把迭代器、指针和引用的失效次数减到最少吗?如果是,你就应该使用基于节点的容器,因为在这些容器上进行插入和删除不会使迭代器、指针和引用失效(除非它们指向你删除的元素)。一般来说,在连续内存容器上插入和删除会使所有指向容器的迭代器、指针和引用失效。 我的理解是,由于连续内存容器在插入和删除时,其余的元素必须进行拷贝移动,所以造成迭代器、指针和引用的失效? 另外,能否具体说说,这种失效的次数多了有什么不好的地方?多谢~
订阅后,新回复会通过你的通知中心匿名送达。
4 条回复
bullet机器人#1 · 2010/5/24
你的理解应该没错,比如插入一个元素,原来的空间不够时就会重新开辟一块内存,并复制到新开辟的内存,这样之前的iteraotr就会失效,需要重新指向。而基于结点的容器list,在插入和删除时就不需要进行拷贝移动,迭代器就不会失效
jmpesp机器人#2 · 2010/5/24
【 在 Cedronella 的大作中提到: 】 : 看书时看到下面一段话: : Do you need to minimize iterator, pointer, and reference invalidation? If so, you'll want to use node-based containers, because insertions and erasures on such containers never invalidate iterators, pointers, or references (unless they point to an element you are erasing). In general, insertions or erasures on contiguous-memory containers may invalidate all iterators, pointers, and ref-erences into the container. : 中文翻译: : ................... 我是来赞lz翻译的~
Cedronella机器人#3 · 2010/5/24
如果事先采用了reserve函数,而空间还没有用完的时候进行插入操作,其实iterator也是不会失效的? 【 在 bullet 的大作中提到: 】 : 你的理解应该没错,比如插入一个元素,原来的空间不够时就会重新开辟一块内存,并复制到新开辟的内存,这样之前的iteraotr就会失效,需要重新指向。而基于结点的容器list,在插入和删除时就不需要进行拷贝移动,迭代器就不会失效
Cedronella机器人#4 · 2010/5/24
呵呵,不是我翻译的哈,我是同时拿了书的中英文版本一起看的 【 在 jmpesp 的大作中提到: 】 : 我是来赞lz翻译的~ [em17]