Reputation: 1163
I have two sets test
and test1
and I need to remove elements from test
that exist in test1
e.g.
if test
contains 1,2,3,4,5 and test1
contains 3,5,6,7: then the function should be performed on test
so only 1,2,4 are left in it.
I've discovered set_intersection - is that the best way of doing things?
edit: apologies. both test
and test1
are set<int>
Upvotes: 1
Views: 411
Reputation: 67221
This should work. I haven't tested it though. You can use :
set_difference(test.begin(), test.end(),test1.begin(),test1.end(),std::inserter(test, test.end()));
Upvotes: 3
Reputation: 7723
set
doesn't have non-const iterator. use list
and remove_if.
#include <iostream>
#include <list>
#include <algorithm>
int
main(int argc, char* argv[]) {
std::list<int> test = {1,2,3,4,5};
std::list<int> test1 = {3,5,6,7};
std::list<int>::iterator ri = std::remove_if(test.begin(), test.end(), [&](int x) -> bool {
return std::find(test1.begin(), test1.end(), x) != test1.end();
});
test.erase(ri, test.end());
std::for_each(test.begin(), test.end(), [&](decltype(test)::value_type x) {
std::cout << x << std::endl;
});
return 0;
}
Upvotes: 0