0

i want to remove overlaps string stored in vector<-string> for show only one element.
i sorted vector dictionary order and it work well.
and next for erase, i use code below.

  for(auto iter = begin(vec); iter != end(vec); iter++) {
        auto frontIter = (iter + 1);

        if((*iter).compare(*frontIter) == 0) 
            vec.erase(iter);
    }

but it erase only one overlap element.
if i input like a a a(3 strings) and all element of vector show a a(2 strings)
i think vec.erase(iter); of part have something wrong..

KJS_999
  • 35
  • 5
  • The `vec.erase()` call invalidates all iterators that refer to (elements of) `vec` at or after `iter`. Your code is assuming the iterators are still valid, so has undefined behaviour. In any event, look up the standard algorithm `unique()`. – Peter Sep 06 '18 at 10:41
  • @Peter thanks for advice. i will check `unique()` at reference, – KJS_999 Sep 06 '18 at 11:00

1 Answers1

1

Put the elements of the vector in a set and then put back to vector will remove all the duplicates.

set<string> s( vec.begin(), vec.end() );
vec.assign( s.begin(), s.end() );

If it is necessary to do with iterator

set<string> s;
for(auto iter = begin(vec); iter != end(vec); iter++)
{
    s.insert(*iter);
}
vec.assign( s.begin(), s.end() );
Rizwan
  • 3,324
  • 3
  • 17
  • 38