Note that there are some explanatory texts on larger screens.

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

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload