问题描述
我知道以下代码对于std :: vectors以及更广泛的所有STL容器都是不正确的:
I know that the following code is not correct, for std::vectors and more generally all STL containers:
std::vector<something>::iterator it = array.begin();
for(; it != array.end(); it++) {
...
array.erase(it);
...
}
因为迭代器需要在擦除和元素后进行更新.
because the iterator needs to be updated after erasing and element.
我想知道增强多重索引是否相同,例如,以下内容是否正确:
I was wondering if it's the same for a boost multi-index, e.g would something like the following be correct or not:
my_index::iterator it = index.get<0>().begin();
for(; it != index.get<0>().end(); it++) {
...
index.erase(it);
...
}
我想确保很好地理解文档的以下段落: http://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#guarantees 这似乎表明我可以在不使迭代器无效的情况下进行擦除.但是,我不确定是否因为删除了一个元素而使本应在迭代过程中访问的另一个元素可以在当前迭代器的位置之前移动并且永远不会被访问(换句话说,通过在迭代过程中擦除一些元素,我仍然确定要遍历所有要素吗?).
I'd like to be sure to understand well the following paragraph of the documentation: http://www.boost.org/doc/libs/1_51_0/libs/multi_index/doc/tutorial/indices.html#guaranteeswhich seems to state that I can erase without invalidating the iterator. However I'm not sure if because I delete an element, another element that I would be supposed to visit during the iteration could be moved before the current iterator's position and never be visited (in other words, by erasing some elements during the iteration, am I still sure to go through all the elements?).
谢谢!
推荐答案
您链接的段落仅适用于哈希(无序)索引.它指出,当插入新元素时,哈希索引迭代器仍然有效.
The paragraph you linked only applies to hashed (unordered) indices. It states that when inserting new elements, hashed index iterators remain valid.
在擦除时,对于有序索引,您始终可以使用erase
中的返回值来保证完整的迭代:
When erasing, for ordered indices you can always guarantee complete iteration by using the return value from erase
:
for (; it != index.get<0>().end(); ) {
if (...) it = index.erase(it);
else ++it;
}
这也适用于哈希(无序)索引,因为迭代顺序在擦除元素上是稳定的.
This will also work for hashed (unordered) indices, as the iteration order is stable over erasing elements.
这篇关于使用迭代器从增强型多索引中删除项目时的一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!