10

我正在尝试调用 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()
);

但是, v 将作为空列表返回。是因为我不能在列表容器上使用它吗?

4

2 回答 2

13

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

于 2012-09-03T18:36:54.417 回答
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()));
于 2012-09-03T18:39:58.943 回答