为什么使用 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);