Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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()));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top