【问题标题】:set union is not working设置联合不工作
【发布时间】:2013-07-19 15:15:50
【问题描述】:

'left' 是 std::set 的 std::vector 对于left(已设置)中的每个元素,我正在尝试通过迭代'left'来对另一个集合进行设置联合操作。

为什么下面的代码不起作用。我正在尝试做两组的集合。

std::vector<std::set<int> > left(num_nodes);
//Both leftv and left are not empty ....there is some code here which fills them.
std::set<int> leftv, dummy; 

for(std::set<int>::iterator u = leftv.begin(); u != leftv.end() ;u++){
    dummy.insert(v);          //v is some integer
    std::set_union (left[*u].begin(), left[*u].end(), dummy.begin(), dummy.end(), left[*u].begin());
    dummy.clear();
}

错误 /usr/include/c++/4.3/bits/stl_algo.h:5078:错误:分配只读位置'__result.std::_Rb_tree_const_iterator<_tp>::operator* with _Tp = int'

【问题讨论】:

  • 您能否详细说明 what 不起作用。编译器错误?运行时崩溃?
  • 您的问题不在于联合,而在于您尝试迭代的方式。你想联合起来做什么? (leftv 是否应该是 left 中所有集合的并集?)
  • 如果这是所有相关代码,那么当到达 for 循环时,leftv 为空,因此您无需迭代。
  • 哪两套?如果您的意思是 leftv 和 dummy,那不是这里发生的事情。您对 set_union 的使用是将左侧的某些项目(集合向量)与虚拟对象合并。您想在这里实现什么
  • @SteveL leftv 只是索引 u 的来源。 union 的集合是 left 的元素和另一个集合 dummy

标签: c++ stl set set-union


【解决方案1】:

您正试图通过将left[*u].begin() 作为set_union 的输出参数来覆盖集合的内容。集合的元素不能被修改,因为它们的值决定了它们在集合中的位置。即使可以,您也需要扩展容器以容纳额外的元素,而不是简单地覆盖现有的元素;并且输出不得与任一输入范围重叠。总结一下:您不能使用set_union 将一组内容插入到另一组中。

如果要将dummy的内容添加到left[*u],那么插入每个元素:

std::copy(dummy.begin(), dummy.end(), std::inserter(left[*u]));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-09
    • 2022-11-11
    • 1970-01-01
    • 2018-10-03
    • 2013-06-05
    • 2012-11-07
    • 1970-01-01
    • 2014-12-25
    相关资源
    最近更新 更多