删除vector.end()失败 [英] Erasing vector.end() fails

查看:78
本文介绍了删除vector.end()失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么使用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().我很好奇到底是什么原因造成的.

I'm a bit new to these iterators , so this caught me off guard. While I know there exists vector.pop_back(). I'm curious to know what exactly causes this.

链接到该程序.

推荐答案

vector::end()并不指向最后一个元素,而是指向最后一个元素之后的元素.

vector::end() does not point to the last element, it points to the element just after the last element.

引用 cplusplus.com

std::vector::end

返回一个迭代器,该迭代器引用 向量容器.

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.

因为标准库函数使用的范围不 包含由其闭合迭代器指向的元素,此函数 通常与vector::begin结合使用以指定范围 包括容器中的所有元素.

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(),因此是错误.

Hence, it has nothing to erase() there, and hence the error.

替换

c.erase(c.end());

使用

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

这篇关于删除vector.end()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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