### Removing vector elements?

Hey guys,

how can I remove (duplicate) vector elements using only .size(), .pop_back(), and .push_back, and without using a second vector?

an example of this (numbers between 1 and 10, length is 10 - this all depends on user input):

vector before: 10 7 10 4 1 0 10 4 9 7
vector after: 10 7 4 1 0 9

Any help would be appreciated! Thanks :)
> without using a second vector?

I suppose that means in O(1) size - ie. without using any auxiliary container at all.

If the order of the non-duplicated values need not be preserved, sort the vector, `std::unique()` (or its equivalent), and then pop off the duplicated values at the back of the sequence.
http://en.cppreference.com/w/cpp/algorithm/unique

If the order of the non-duplicated values must be preserved, something like this:
 ``1234567891011121314151617`` ``````std::vector seq = { 10, 7, 10, 4, 1, 0, 10, 4, 9, 7 } ; for( std::size_t i = 0 ; i < seq.size() ; ++i ) { std::size_t j = i + 1 ; while( j < seq.size() ) // for every element after i { if( seq[i] == seq[j] ) // if it is a duplicate { // move all elements after it by one position to the left for( std::size_t k = j+1 ; k < seq.size() ; ++k ) seq[k-1] = seq[k] ; seq.pop_back() ; // and pop off the last element } else ++j ; } }``````

Last edited on
Topic archived. No new replies allowed.