简体   繁体   English

C++ 中的分段错误 - 向量

[英]Segmentation Fault in C++ - Vectors

#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() 
{
    int a, b;
    cin>>a;
    vector<int> numbers;
    for(int i=0; i<a; i++)
    {
        cin>>b;
        numbers.push_back(b);
    }

    int c,d,e;
    cin>>c;
    numbers.erase(numbers.begin()+c-1);
    cin>>d>>e;
    numbers.erase(numbers.begin()+d-1, numbers.end()+e);

    cout<<numbers.size();
    for(int x : numbers)
        cout<<x<<" ";

    return 0;
}

Hello everyone, I am learning c++ and writing a very simple program, but this code is giving "Segmentation Fault" as error.大家好,我正在学习 c++ 并编写了一个非常简单的程序,但是这段代码给出了“Segmentation Fault”错误。 I really could not figure out why this is happening.我真的不明白为什么会这样。

Thank you.谢谢你。

This line这条线

numbers.erase(numbers.begin()+d-1, numbers.end()+e);

cannot be correct.不可能是正确的。 Incrementing the end iterator never gets you a valid iterator.递增end迭代器永远不会得到一个有效的迭代器。 It is not quite clear what you want to do, but if you want to erase elements in the range of indices [d,e) then that would be目前还不太清楚你想做什么,但如果你想删除索引[d,e)范围内的元素,那将是

numbers.erase(numbers.begin()+d, numbers.begin()+e);

Note: No +1 needed on the first, because the first is inclusive.注意:第一个不需要+1 ,因为第一个包含在内。 And you get an iterator to the e -th element by incrementing the begin iterator not the end iterator (well... I assume the common 0-based counting, ie the "first" element is the 0th element;).并且您通过递增begin迭代器而不是end迭代器来获得第e个元素的迭代器(嗯......我假设常见的基于 0 的计数,即“第一个”元素是第 0 个元素;)。

Also, as mentioned in comments, you should check if the user entered values are in range, before calling erase .此外,如评论中所述,您应该在调用之前检查用户输入的值是否在范围内erase erase does no bounds-checking. erase没有边界检查。 If you pass invalid iterators your get undefined behavior.如果您传递无效的迭代器,您将获得未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM