Re: STL - erasing from a set
On 11/19/2010 08:14, Andrey wrote:
You said,
This basically means you would need a
temporary container and it does not remove the mentioned elements from
the source set.
I understand that, but the problem is that this temporary container
cannot be a new (empty) set... it needs to be something that is filled
to the necessary capacity already. I wrote another sample program to
see if I could I could get set_symmetric_difference to work:
#include<iostream>
#include<cstdlib>
#include<set>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
set<int> set_int;
set_int.insert(2);
set_int.insert(1);
set_int.insert(3);
set<int> set2_int;
set2_int.insert(2);
set<int> set_diff;
set_symmetric_difference(set_int.begin(), set_int.end(),
set2_int.begin(), set2_int.end(), set_diff.begin());
return 0;
}
of course, this fails with
[compiler curses omitted]
This is understandable, because
a) the iterator of set are const iterators.
b) there is no memory yet to insert (This means the compile time error
prevents a nasty runtime error here)
Just use an insert iterator adaptor like so for your last line:
std::set_symmetric_difference(set_int.begin(), set_int.end(),
set2_int.begin(), set2_int.end(),
std::inserter(set_diff, set_diff.begin()));
Of course, I could use std::set::erase to erase each value
individually, as you mention. But that means I would have to create a
loop. I thought there should be a way to do this in STL in a single
line.
With a C++0x-capable compiler you can write a single line:
std::for_each(set2_int.begin(), set2_int.end(),
[&](const std::set<int>::value_type& r) { set_int.erase(r); });
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]