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.
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;
} );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With