Re: STL - erasing from a set
On 19 nov, 08:14, Andrey <akr...@gmail.com> 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.
You can insert into an empty set using a special iterator:
std::insert_iterator<>. You usually create this iterator using the
std::inserter<>() function.
I wrote another sample program to
see if I could I could get set_symmetric_difference to work:
.......
set_symmetric_difference(set_int.begin(), set_int.end(),
set2_int.begin(), set2_int.end(), set_diff.begin());
The set_diff.begin() iterator hasn't got the right iterator type. You
need an output iterator.
See my code:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <set>
int main(int argc, char* argv[])
{
typedef std::set<int> set_int_t;
set_int_t A, B, C;
/// A contains [0, 19]
for(int i(0); i<20; ++i)
A.insert(i);
/// B contains [10, 29]
for(int i(10); i<30; ++i)
B.insert(i);
/// C will contains [0,9]
/// using std::set_symmetric_difference()
/// would make C contains [0,9] U [20,29]
std::set_difference(
A.begin(), A.end(),
B.begin(), B.end(),
std::inserter(C, C.begin()));
/// Swapping A and C, and erasing C
A.swap(C);
C.clear();
/// Show the content of A
std::cout << "A = { ";
std::copy(
A.begin(), A.end(),
std::ostream_iterator<int>(std::cout, ", "));
std::cout << "}" << std::endl;
return 0;
}
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.
You can swap the two sets. A.swap(C); makes all the content of C goes
into A and all the content of A goes into C. As you don't care anymore
of previous A's content, you can just clear C afterward. C.clear();
Frederic JARDON
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]