C ++ Segmentation error without pointers (HackerRank)

I solved the problem in ranking hackers.

Input format . The first line of input contains an integer N. The next line contains N integers, separated by spaces. The third line contains a single integer x, indicating the position of the element that should be removed from the vector. The fourth line contains two integers a and b, indicating the range that should be removed from the vector, including a and excluding b.

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

CODE:

#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; } 

But with this test case, a “Segmentation Error” occurs:

 6 1 4 6 2 8 9 2 2 4 

Can you help me review my code and provide some feedback on what the problem is?

EDIT

Thanks @john for the answer. Here's what it looks like without a seg crash:

 #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; } 
+4
source share
1 answer

You are trying too hard to use your input code. This is incorrect because you believe that cin.ignore() skip the rest of the line when it skips only the next character (it could be a space). I assume this is the reason seg failed. You can find out how many numbers you should read after reading the first. There is no need to use getline or stringsteam at all.

You do not need a vm vector. It will always contain two values, so just declare two variables. You can also choose much better names for all of your variables.

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

All Articles