列表容器上的std :: set_difference

Dyn*_*ght 9 c++ stl list set-difference

我正在尝试调用set_difference函数,并将结果放在std :: list上.从理论上讲,可以在任何已分类的容器上执行此操作,对吗?

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()
);
Run Code Online (Sandbox Code Playgroud)

然而,v作为空列表返回.是因为我不能在列表容器上使用它吗?

Pet*_*ker 12

这是因为v.begin()是一个空序列的开始.这些元素几乎可以复制到任何地方.替换为std::back_inserter(v).这将为您提供一个知道如何插入的迭代器v.


old*_*inb 6

您需要提供将插入的输出迭代器.尝试使用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()));
Run Code Online (Sandbox Code Playgroud)