문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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()));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top