Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::set_difference on list container

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?

like image 332
Dynelight Avatar asked Sep 03 '12 18:09

Dynelight


2 Answers

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.

like image 153
Pete Becker Avatar answered Nov 20 '22 17:11

Pete Becker


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()));
like image 6
obataku Avatar answered Nov 20 '22 15:11

obataku