gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:16:35 25 4
gpt4 key购买 nike

我在 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, x = 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() 将跳过该行的其余部分,而它只跳过下一个字符(可能是空格)。我想这就是段错误的原因。读完第一个数字后,您可以说出必须读多少个数字。根本不需要使用 getlinestringsteam

您不需要 vm vector 。它总是包含两个值,所以只需声明两个变量。您还可以为所有变量选择更好的名称。

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

关于没有指针的 C++ 段错误 (HackerRank),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31933579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com