Assume that I have a string 'abcd', and a vector [4,1,3,2] to index the string. For example, first element of vector is 4, so I should remove 4th character in 'abcd' which refers to 'd'. Then the second element of vector is 1, so I should remove 1st character in 'abcd' which refers to 'a', and so on. I want to record the operated string every time I remove one character. And here is my code:
# include <iostream>
# include <vector>
using namespace std;
int main()
{
int m;
cin >> m;
string T;
cin >> T;
cout << T << endl;
vector<int> arr(m);
for(auto &x : arr) cin >> x;
// Remove character from string at given index position
for (int i = 0; i < m; i++){
T.erase(T.begin() + arr[i]-1);
cout << T << endl;
}
return 0;
}
However, I had faced some problem in the output, how could I fix it?
4
abcd
abcd
4 1 3 2
abc
bc
Segmentation fault
You confuse the indicies of the characters in the original string with the indices of same characters in the updated string.
Consider the string
aband erasing characters at position0and1(indices are 0 based). Then you first remove the first character and have the new stringb. Now you cannot remove the character at index1anymore, because there is none. The characterbthat was at position1in the original string is now at index0.As mentioned in a comment, the most simple is to keep the original string intact so you can use its indices and keep track of "removed" indices in a seperate vector:
Note that I assumed the input uses 0-based indices. If the input uses 1-based indices, I would correct for that as early as possible while taking input.