c++ - 当我调用它两次时,set_union 得到了错误的结果

标签 c++ algorithm stl set-union

这个问题让我困惑了好几个小时, 请帮我! 第一次调用set_union结果正确,第二次调用结果错误,看代码:

std::vector<int> set1{ 1, 2, 3, 4, 5, 6 };
std::vector<int> set2{ 4, 5, 6, 7, 8 };
std::vector<int> result{};

std::set_union(std::begin(set1), std::end(set1),
    std::begin(result), std::end(result), 
    std::back_inserter(result));  
// result is 1 2 3 4 5 6

std::back_insert_iterator< std::vector<int>> back2 =
    std::set_union(std::begin(set2), std::end(set2), 
        std::begin(result), std::end(result), 
        std::back_inserter(result)); 

我调试上面的代码,得到这个结果:

[0] 1   int
[1] 2   int
[2] 3   int
[3] 4   int
[4] 5   int
[5] 6   int
[6] 1   int
[7] - 572662307 int
[8] - 572662307 int
[9] - 572662307 int
[10] - 572662307    int
[11] - 572662307    int
[12]    4   int
[13]    5   int
[14]    6   int
[15]    7   int
[16]    8   int

最佳答案

The resulting range cannot overlap with either of the input ranges. https://en.cppreference.com/w/cpp/algorithm/set_union

你为什么不用这个?

 std::set_union(std::begin(set1), std::end(set1), 
    std::begin(set2), std::end(set2), 
    std::back_inserter(result)); 

关于c++ - 当我调用它两次时,set_union 得到了错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56000158/

相关文章:

c++ - STL 对嵌套类排序

c++ - 如何减少用户数据类型符号? (类型定义?)

algorithm - Timsort 如何在某些情况下超越 O(n log n) 排序界限?

asp.net - 使用 ASP.NET(算法)创建 (FTP) 移动文件守护进程

c++ - 将 STL 算法限制为 N 个元素

c++ - 与多组件 key 的快速部分匹配

C++ Qt 无法读取整个文本文件

c++ - 结构错误 :"no matching function for call to "

c++ - CreateMutex 和 OpenMutex 返回 NULL

javascript - Node, Javascript 中的算法优化