在迭代时从STL集中删除元素 [英] Deleting elements from STL set while iterating

查看:167
本文介绍了在迭代时从STL集中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过一个集合,并删除符合预定义标准的元素。

I need to go through a set and remove elements that meet a predefined criteria.

这是我写的测试代码:

#include <set>
#include <algorithm>

void printElement(int value) {
    std::cout << value << " ";
}

int main() {
    int initNum[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    std::set<int> numbers(initNum, initNum + 10);
    // print '0 1 2 3 4 5 6 7 8 9'
    std::for_each(numbers.begin(), numbers.end(), printElement);

    std::set<int>::iterator it = numbers.begin();

    // iterate through the set and erase all even numbers
    for (; it != numbers.end(); ++it) {
        int n = *it;
        if (n % 2 == 0) {
            // wouldn't invalidate the iterator?
            numbers.erase(it);
        }
    }

    // print '1 3 5 7 9'
    std::for_each(numbers.begin(), numbers.end(), printElement);

    return 0;
}

首先,我想从集合中删除一个元素,将使迭代器无效,并且在for循环的增量将具有未定义的行为。即使我执行了这个测试代码,一切顺利,我不能解释为什么。

At first, I thought that erasing an element from the set while iterating through it would invalidate the iterator, and the increment at the for loop would have undefined behavior. Even though, I executed this test code and all went well, and I can't explain why.

我的问题:
这是std集的定义的行为还是这个实现具体?我在ubuntu 10.04(32位版本)上使用gcc 4.3.3。

My question: Is this the defined behavior for std sets or is this implementation specific? I am using gcc 4.3.3 on ubuntu 10.04 (32-bit version), by the way.

谢谢!

建议的解决方案:

这是从集合中迭代和删除元素的正确方法吗?

Is this a correct way to iterate and erase elements from the set?

while(it != numbers.end()) {
    int n = *it;
    if (n % 2 == 0) {
        // post-increment operator returns a copy, then increment
        numbers.erase(it++);
    } else {
        // pre-increment operator increments, then return
        ++it;
    }
}

编辑:PREFERED SOLUTION

我发现了一个对我来说更加优雅的解决方案,即使它完全一样。

I came around a solution that seems more elegant to me, even though it does exactly the same.

while(it != numbers.end()) {
    // copy the current iterator then increment it
    std::set<int>::iterator current = it++;
    int n = *current;
    if (n % 2 == 0) {
        // don't invalidate iterator it, because it is already
        // pointing to the next element
        numbers.erase(current);
    }
}

如果在while期间有几个测试条件,其中一个必须增加迭代器。我喜欢这个代码更好,因为迭代器只增加只在一个地方,使代码更容易出错和更易读。

If there are several test conditions inside the while, each one of them must increment the iterator. I like this code better because the iterator is incremented only in one place, making the code less error-prone and more readable.

推荐答案

这取决于实现:

标准23.1.2.8:

Standard 23.1.2.8:


插入成员不应影响迭代器和容器引用的有效性,擦除成员只能使迭代器和对已删除元素的引用无效。

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

也许你可以试试这 - 这是标准的符合:

Maybe you could try this -- this is standard conforming:

for (it = numbers.begin(); it != numbers.end(); ) {
    if (*it % 2 == 0) {
        numbers.erase(it++);
    }
    else {
        ++it;
    }
}

注意,++是后缀,

2015.10.27更新:
C ++ 11已经解决了缺陷。 迭代器擦除(const_iterator position); 返回一个迭代器到最后一个元素删除后的元素(或set :: end,如果最后一个元素被删除)。所以C ++ 11风格是:

2015.10.27 update: C++11 has resolved the defect. iterator erase (const_iterator position); return an iterator to the element that follows the last element removed (or set::end, if the last element was removed). So C++11 style is:

for (it = numbers.begin(); it != numbers.end(); ) {
    if (*it % 2 == 0) {
        it = numbers.erase(it);
    }
    else {
        ++it;
    }
}

这篇关于在迭代时从STL集中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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