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..

2
  • 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(). Commented Sep 6, 2018 at 10:41
  • @Peter thanks for advice. i will check unique() at reference, Commented Sep 6, 2018 at 11:00

1 Answer 1

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() );
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.