Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to delete/erase duplicate elements from std::vector while maintaining order? [duplicate]

Tags:

c++

stl

vector

Is there a way to delete duplicate elements from vector container containing string elements while maintaining order.

Till now I have used set method, but it doesn't retain the order.

I don't know how to use remove_if with respect to this problem.

like image 424
Quoros Avatar asked Dec 21 '22 02:12

Quoros


2 Answers

How about using a temporary container:

std::vector< int >::iterator i , j ;
std::set< int > t_set;
for( i = v.begin() , j = v.begin() ; i != v.end() ; ++i )
    if( t_set.insert( *i ).second) 
        *j++ = *i ;
v.erase( j , v.end() ); 

Using std::remove_if, I can think of this:

std::set<int> t_set;
std::vector<int> res; //Resultant vector

remove_copy_if(v.begin(), v.end(), std::back_inserter(res), 
    [&t_set](int x){ 
        return !t_set.insert(x).second; 
    } );
like image 122
P0W Avatar answered Mar 23 '23 00:03

P0W


You could create an empty array, then iterate over the original vector and only copy over the first instance of each item in the vector. You could keep track of whether or not you've seen an item yet in the vector by adding it to a set and checking for an items presence in the set before adding it to the new array.

like image 37
Madison May Avatar answered Mar 22 '23 23:03

Madison May