First, you should read the input into a character and use push_back()
to save the read character into the string.
cin>>n;
for(int i=0;i<n;i++)
{
char c;
cin>>c;
masiv.push_back(c);
}
You are getting segmentation fault because you save the size of the string into value n (n=masiv.size();
) which you shouldn't because once you erase an element from the string, its size changes. Therefore you should use size()
method for the loop boundary as below.
for(int i=0;i<masiv.size();i++)
{
for(int j=0;j<masiv.size();j++)
{
if(masiv[i]==masiv[j] && i!=j)
{
masiv.erase(j, 1);
j--;
}
}
}
See how smiple erase()
method is? Just erase the repeated element (latter one). j
specifices the indice of the repeated element and 1
specifies the character count that will be deleted starting from that indice. You have to decrement j
because once you erase the character at the jth indice, now j will be pointing to the next character. When inner loop continues it will increment j
. If you do not adjust the indice after erasing a character, you will skip a character when the loop increments. You have to adjust j
to point to the correct index. Therefore j--;
.
Edit: Better loops
You can re-arrange your loops in a way that you do not have to check whether i==j
or not. Just start the inner loops index just 1 larger than that of outer loops.
for(int i=0;i<masiv.size();i++)
{
for(int j=i+1;j<masiv.size();j++)
{
if(masiv[i]==masiv[j])
{
masiv.erase(j--, 1);
}
}
}
Assume you have entered level
as the string. The outer loop starts from l
and inner loop starts from e
. By this way you make less iterations and guarantee not to compare same indices.