"James Juno" <juno@noplace.fake> wrote in message
news:GbadnTVsYtsMZf3UnZ2dnUVZ_uudnZ2d@scnresearch.com...
Hi folks,
Rudimentary container question. I have something like
std::vector<int> v1;
std::vector<int> v2;
For analysis purposes we will call the number of elements in v1 "N", and
the number of elements in V2 "M". Right now, besided the correcctness
issues, you have an O(N*M) algorithm.
I want to remove all elements in v2 from v1. Right now I'm using this
horrible non-STL loop:
for ( size_t i = 0; i < v1.size(); ++i )
for ( size_t j = 0; j < v2.size(); ++j )
{
if ( v1[i] == v2[j] )
{
v1.erase( v1.begin() + i );
break;
}
}
Yuck. There has got to be a cleaner, more STL-like way of doing this.
That is not very efficent in the first place. O(N*M).
If it is not a problem, the simplest solution is to sort them both, and
use the std::set_difference algorithm.
std::sort(v1.begin(),v1.end());
std::sort(v2.begin(),v2.end());
v1.erase(
std::set_difference(
v1.begin(),
v1.end(),
v2.begin(),
v2.end(),
v1.begin()),
v1.end());
for set_difference does not overlap with either input range.