使用迭代器从增强型多索引中删除项目时的一致性 [英] Consistency when removing items from boost multi-index using an iterator

查看:115
本文介绍了使用迭代器从增强型多索引中删除项目时的一致性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道以下代码对于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);
   ...
}

我想确保很好地理解文档的以下段落:

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#guarantees which 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.

这篇关于使用迭代器从增强型多索引中删除项目时的一致性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆