-4

In this program I have a string which I pass as a parameter to a function. I want the function to erase all adjacent letters from a string containing only letters from a-z, always ordered alphabetically. For example if i enter aaabbccd, the program ought to output ad. I want to ask why the program stops working?

#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<char> rez;
string reduce_string(string s)
{
    for(int i=0; i<s.length()-1; i++)
    {
        if(s[i]==s[i+1])
        {
            s[i]=s[i+1]='0';
            s.erase(i);
            s.erase(i+1);
        }

    }
    return s;
}
int main()
{

    string s;
    cin >> s;
    cout<<reduce_string(s);

    return 0;

}
P.Petrov
  • 5
  • 3

2 Answers2

0

Your return is inside the loop - the loop will only run on the first character then return.

lxop
  • 7,596
  • 3
  • 27
  • 42
0

After the first erase(i) all the characters shift one left and the indices change. Instead of calling s.erase(i+1) you have to call again s.erase(i) to not try to access beyond the end of the string:

s.erase(i);
s.erase(i);

or just s.erase(i, 2).

Scott
  • 1,863
  • 2
  • 24
  • 43
Mihayl
  • 3,821
  • 2
  • 13
  • 32