加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

没有指针的C分段错误(HackerRank)

发布时间:2020-12-16 07:13:18 所属栏目:百科 来源:网络整理
导读:我解决了Hacker Rank中的一个问题. Input Format. The first line of the input contains an integer N.The next line contains N space separated integers.The third line contains a single integer x,denoting the position of an element that should b
我解决了Hacker Rank中的一个问题.

Input Format. The first line of the input contains an integer N.The next line contains N space separated integers.The third line contains a single integer x,denoting the position of an element that should be removed from the vector.The fourth line contains two integers a and b denoting the range that should be erased from the vector inclusive of a and exclusive of b.

Output Format. Print the size of the vector in the first line and the elements of the vector after the two erase operations in the second line separated by space.

码:

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

int main() {
    int n = 0,x = 0,value = 0;
    vector<int> vk,vm;
    vk.reserve(100000);
    string k,m;

    cin >> n;
    cin.ignore();
    getline(cin,k);
    cin >> x;
    cin.ignore();
    getline(cin,m);

    stringstream sk(k);
    while (sk >> value)
        vk.push_back(value);

    stringstream sm(m);
    while (sm >> value)
        vm.push_back(value);

    vk.erase(vk.begin() + x-1);
    vk.erase(vk.begin() + vm[0]-1,vk.begin() + vm[1]-1);

    cout << vk.size() << endl;
    for (int i = 0; i < vk.size(); i++)
        cout << vk[i] << " ";

    cout << endl;
    return 0;
}

但是这个测试用例会产生“分段错误”:

6
1 4 6 2 8 9
2
2 4

你能帮我看看我的代码并提供一些关于问题的反馈吗?

编辑

Thanks to @john for the answer. Here is how it looks without the seg fault:

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

int main() {
    int n = 0,y = 0,z = 0,value = 0;
    vector<int> vk;
    vk.reserve(100000);

    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> value;
        vk.push_back(value);
    }
    cin >> x >> y >> z;

    vk.erase(vk.begin() + x-1);
    vk.erase(vk.begin() + y-1,vk.begin() + z-1);

    cout << vk.size() << endl;
    for (int i = 0; i < vk.size(); i++)
        cout << vk[i] << " ";

    cout << endl;
    return 0;
}

解决方法

你输入的代码太难了.这是不正确的,因为你似乎假设cin.ignore()将跳过该行的其余部分,当它只跳过下一个字符(可能是一个空格).我猜这是seg故障的原因.您可以在阅读第一个数字后告诉您需要阅读多少个数字.根本不需要使用getline或stringsteam.

你不需要vm向量.它将始终包含两个值,因此只需声明两个变量.您还可以为所有变量选择更好的名称.

cin >> n;
for (int i = 0; i < n; ++i)
{
    cin >> value;
    vk.push_back(value);
}
cin >> x >> vm0 >> vm1;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读