-1

Excuse me does anyone here know how can we remove duplicates from a string using unique func or any other func?

for example if i want to turn "fdfdfddf" into "df" I wrote the code below but it seems it doesn't work

#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<int>t;
    int n;
    cin>>n;
    string dd;
    vector<string>s;
    for(int i=0;i<n;i++)
    {
        cin>>dd;
        s.push_back(dd);
       sort(s[i].begin(),s[i].end());
     unique(s[i].begin(),s[i].end());
      cout<<s[i]<<"\n";
    }

}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
hemetaf
  • 1
  • 2
  • 3
    https://en.cppreference.com/w/cpp/algorithm/unique - read the docs, study the examples. Also please read this: https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h and https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Mat Mar 05 '22 at 11:59
  • @Sneftel, what does removing duplicate strings from an array have to do with with removing duplicate substrings from a string? I've voted to reopen. – Cary Swoveland Mar 05 '22 at 19:24
  • If duplicates of the strings `'f'` and `'d'` are removed from `'fdfdfddf'`, an empty string is returned. I assume from your example that duplicate strings must contain at least two characters. That needs to be clarified. – Cary Swoveland Mar 05 '22 at 19:35
  • 1
    You have not told us precisely what you are trying to do. Suppose the string were `'fddfddf'`. The repeated substrings of length two or more are `'fd'`, `'df'`, `'dd'` and `'fdd'`. How are these substrings to be used to produce a result? – Cary Swoveland Mar 05 '22 at 20:09

1 Answers1

2

According to the documentation, unique:

Eliminates all except the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

If you want to get rid of the excessive elements, you have to do that explicitly, e.g., by calling erase (as in the example in the documentation):

auto last = std::unique(s[i].begin(), s[i].end());
s[i].erase(last, s[i].end());
nickie
  • 5,608
  • 2
  • 23
  • 37