c++ - vector 删除无需设置 iter 返回值即可工作

标签 c++

我们都知道在 for 中使用 erase 时,我们必须重新设置 iter,比如 iter = vector.erase(iter),因为 erase 选项会使 iteraor 失效。但是我发现,不重置也可以,代码如下:

int main() {
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    a.push_back(2);
    a.push_back(10);
    a.push_back(11);
    for (vector<int>::iterator iter = a.begin(); iter != a.end();) {
        if (*iter == 2) {
            // iter = a.erase(iter); the same 
            a.erase(iter);
            continue;
        } else {
            iter++;
        }
    }
    for (vector<int>::iterator iter = a.begin(); iter != a.end(); iter++) {
        cout << *iter << " ";
    }
    cout << endl;
    return 0;
}

代码运行成功,输出:1 3 10 11。

所以我的问题是“a.erase(iter)”在这段代码中得到的结果与“iter = a.earse(iter)”相同?

最佳答案

您看到的是未定义的行为。

来自 http://en.cppreference.com/w/cpp/container/vector/erase (强调我的)

Removes specified elements from the container.
1) Removes the element at pos.
2) Removes the elements in the range [first; last).

Invalidates iterators and references at or after the point of the erase, including the end() iterator.

通过使用

a.erase(iter);
continue;

您正在访问一个无效的迭代器。

关于c++ - vector 删除无需设置 iter 返回值即可工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31758025/

相关文章:

c++ - 将文件 (.a) 链接到共享对象 (.so)

c++ - 为什么 TRACE 会停止运行?

c++ - 为什么不从不同的继承分支覆盖纯虚方法?

c++ - 显式类型转换与使用类型规则

c++ - 如何声明和定义全局变量以便从所有头文件/源文件中正确访问它们

c++ - 如果模板类型本身就是模板,如何获取迭代器?

c++ - 禁止 Clang-Format 乱用评论

c++ - 如何使用 SIMD 比较两个 char vector 并将结果存储为 float ?

c++ - 在opencv中获取纸币的边界框

c++ - 如何在代码块中链接 winpcap?