Deleting double elements in a vector
for( int i = 0; i < (p.size()-1); i++ )
{
for( int j = i+1; j <p.size(); j++ )
{
if( p[i]==p[j] )
{
p.erase(p.begin()+j);
}
}
}
Dear All,
I want to deleete all duplicate elemnts in a vector (p) : Afore given piece of code tries to resolve my endeavour bit it does not work. Can someone tell me why?
Thank you
[443 byte] By [
lontana] at [2007-11-20 11:59:26]

# 3 Re: Deleting double elements in a vector
for( int i = 0; i < v.size(); i++ )
{
cout<<"size="<<v.size()<<endl;
cout<<"i="<<i<<endl;
}
This question is not directly related with the thread but still it is part of the code given in the thread. This snippet looks OK but when I run the program I get normal values for the vector size (11, 12, 13, etc) but very strange value for the counter (10572ACC1, 10572ACC2 etc.)
I have not used counter anywhere lese in the programm, I checked the vector elements and they are OK. Where is the problem?
Thank you
# 4 Re: Deleting double elements in a vector
1) I'm not sure what is going on in your last post. Could you post
a complete program that shows the problem ?
2) when erasing from a vector, that iterator and all iterators after
it are invalidated. I think this is basically what is causing problems
with your code. I THINK that the folowing modification to your code
should be OK (but I'm not sure without giving it more thought):
for( int i = 0; i < (v.size()-1); i++ )
{
for( int j = i+1; j <v.size(); /* nothing here */ )
{
if( v[i]==v[j] )
{
v.erase(v.begin()+j);
}
else
{
++j;
}
}
}
Even if iy works, it will be slow for large data sets (its complexity
is O(N*N)
Here are a couple of other methods that are O(N*LogN).
1) If you can change the order of the vector: sort it ... then
use std::unique to get rid of duplicates.
sort(v.begin(),v.end());
v.erase( unique(v.begin(),v.end()) , v.end() );
2) If you can not change the order, but you can use extra memory
you can do the following: create a set<T> ... loop thru the vector
and attempt to add the elemnt to the set. If it fails, then the
element was already in the set (so it was already in the vector).
You would erase that element.
set<int> s;
vector<int>::iterator it=v.begin();
while (it != v.end())
{
if ( !s.insert(*it).second )
{
it = v.erase(it);
}
else
{
++it;
}
}