简体   繁体   English

列表容器上的std :: set_difference

[英]std::set_difference on list container

I'm trying to call the set_difference function, and put the result on a std::list. 我正在尝试调用set_difference函数,并将结果放在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. 然而,v作为空列表返回。 Is it because I can't use it on the list container? 是因为我不能在列表容器上使用它吗?

It's because v.begin() is the beginning of an empty sequence. 这是因为v.begin()是空序列的开头。 The elements get copied to pretty much anywhere. 这些元素几乎可以复制到任何地方。 Replace it with std::back_inserter(v) . 将其替换为std::back_inserter(v) That will give you an iterator that knows how to insert into v . 这将为您提供一个知道如何插入v的迭代器。

You need to supply an output iterator that will insert . 您需要提供将插入的输出迭代器。 Try using std::inserter . 尝试使用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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM