无法在std::set上使用set_intersection

unable to use set_intersection on std::set

本文关键字:set intersection std      更新时间:2023-10-16

我试图使用set_intersection如下所述

std::set<std::pair<char*, int>,FileLinePairComapare > netSet;
std::set<std::pair<char*, int>,FileLinePairComapare > portSet;
std::set<std::pair<char*, int>,FileLinePairComapare> result;
std::set<std::pair<char*, int>,FileLinePairComapare>::iterator it;
std::set_intersection(netSet.begin(),netSet.end(),portSet.begin(),portSet.end(),result.begin());

我在最后一行得到编译错误

在实例化' _OIter ' std::set_intersection(_IIter1, _IIter1,_IIter2, _IIter2, _OIter) [with _IIter1 = std::_Rb_tree_const_iterator>;_IIter2 =std:: _Rb_tree_const_iterator>;_OIter =std:: _Rb_tree_const_iterator>]:

传递' const std::pair '作为' this '参数"std:: pair&一对std::::操作符= (constStd::pair&) '放弃限定符[-fpermissive]

没有cons函数,我使用这些集合和set_intersection

不能使用算法直接写入std::set迭代器。所有 set迭代器都是const,因为改变任何值都会破坏树(同样适用于std::map键- map迭代器只能修改映射的值)。

即使你可以,它也不会工作,因为容器是空的(例如,如果你试图使用std::vector作为目标容器,你最终会有未定义的行为)。

使用std::inserter

std::set_intersection(
  netSet.begin(), netSet.end(),
  portSet.begin(), portSet.end(),
  std::inserter(result, result.end())
);