10

I'm trying to call the set_difference function, and put the result on a std::list. In theory, it is possible to do this on any sorted container, right?

list<int> v;         

list<int> l1;  
list<int> l2;                   

list<int>::iterator it;

//l1 and l2 are filled here

l1.sort();
l2.sort();

it=set_difference(
   l1.begin(),
   l1.end(), 
   l2.begin(),
   l2.end(), 
   v.begin()
);

v is returning as an empty list, however. Is it because I can't use it on the list container?

Dynelight
  • 2,072
  • 4
  • 25
  • 50

2 Answers2

14

It's because v.begin() is the beginning of an empty sequence. The elements get copied to pretty much anywhere. Replace it with std::back_inserter(v). That will give you an iterator that knows how to insert into v.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Thank you very much. I had another problem: I am doing it=set_difference(...) and it was giving me a compilation error. Fixing that + adding your function did the trick. – Dynelight Sep 03 '12 at 21:44
6

You need to supply an output iterator that will insert. Try using std::inserter.

std::list<int> a { 
  10, 10, 10, 11, 11, 11, 12, 12, 12, 13
};
std::list<int> b {
  10
};
std::list<int> diff;
std::set_difference(a.begin(), a.end(), b.begin(), b.end(),
    std::inserter(diff, diff.begin()));
obataku
  • 29,212
  • 3
  • 44
  • 57