c++ - 删除 vector.end() 失败

标签 c++ vector stl iterator

<分区>

为什么使用 vector.erase(vector.end()) 会产生一个

Segmentation fault (core dumped)

使用此代码时:

#include <iostream>
#include <vector>
using namespace std;

void printMe(vector<int>& v){ for(auto &i:v) cout<<i<<" "; cout<<"\n"; }

int main() {
    vector<int> c = { 1,2,3,4,5,6,7,8};
    printMe(c);
    c.erase(c.begin());
    printMe(c);
    c.erase(c.begin());
    printMe(c);
    // c.erase(c.end()); //will produce segmentation fault
    // printMe(c);
    return 0;
}

我对这些迭代器有点陌生,所以这让我措手不及。虽然我知道存在 vector.pop_back()。我很想知道究竟是什么原因造成的。

A link到程序。

最佳答案

vector::end() 不指向最后一个元素,它指向最后一个元素之后的元素。

引用 cplusplus.com ,

std::vector::end

Returns an iterator referring to the past-the-end element in the vector container.

The past-the-end element is the theoretical element that would follow the last element in the vector. It does not point to any element, and thus shall not be dereferenced.

Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with vector::begin to specify a range including all the elements in the container.

因此,它没有任何东西可以 erase() 在那里,因此错误。


替换

c.erase(c.end());

c.erase(c.end() - 1);

关于c++ - 删除 vector.end() 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29530190/

相关文章:

c++ - 推回 vector 指针时如何解决读取访问冲突

c++帮助将 vector 索引传递给函数

c++ - 这个 auto_ptr 程序是如何工作的,它做了什么?

c++ - 了解 C++ 中的零和 NULL

r - 通过R中的4步以交替方式组合2个向量

C++:如何用两个迭代器构造对象?

c++ - C++17 中 std::unary_function 的等效替代品是什么?

c++ - 如何将 std::<list>::reverse_iterator 与运算符 + 一起使用?

c++ - C++ 中优雅的函数定义

c++ - 构建 vector 时如何去除(一个)不必要的拷贝?