STL set intersection question

P

Phil

Hello,

I'm trying to get the result of a set intersection and I'm sure that I've
made a very basic error.

A Google search has helped but I'm still not quite there. Can someone show
me the error?

set<int> firstSet;

secondSet.insert(1);
secondSet.insert(2);

set<int> secondSet;

secondSet.insert(2);

set<int> resultSet;

resultSet = set_intersection(firstSet.begin(), firstSet.end(),
secondSet.begin(), secondSet.end(), resultSet.begin());
 
P

Pete Becker

Phil said:
resultSet = set_intersection(firstSet.begin(), firstSet.end(),
secondSet.begin(), secondSet.end(), resultSet.begin());

First, set_intersection returns an iterator that points past the end of
the result sequence. Don't assign it to the container, both because it
doesn't make sense to do that and because set doesn't have an assignment
operator that takes an iterator.

More important, though: that last argument, resultSet.begin(), isn't
right. You need an output sequence, that is, a sequence whose elements
are writable. resultSet has no elements, and even if it did, writing
directly to them through that iterator isn't allowed. You need an
insertion iterator here: inserter(resultSet, resultSet.begin()) will do
the job. Assigning to the dereferenced iterator inserts a new element in
the container.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top