形成两组的并集似乎给出了错误且不一致的答案

Forming the union of two sets seems to give wrong and inconsistent answers

本文关键字:错误 答案 不一致 两组      更新时间:2023-10-16

下面的代码是我试图用空集{}形成两个元素集{2,3}的并集。我希望得到的容器(在本例中是一个列表)的大小应该是2。

但是,当我运行代码时,我得到并集的大小是0或3,这取决于变量united声明的两个指示位置中的哪一个。这两个结果都不是我所期望的,它们显然不可能都是正确的。

我在这里错过了什么?

#include <list>
#include <set>
#include <algorithm>  
#include <iostream>
using namespace std;
int main()
{
    //list<int> united; // resulting output is 3
    int d1[] = {2,3};
    set<int> dom1(d1, d1+2);
    set<int> dom2;
    list<int> united; // resulting output is 0
    set_union(dom1.begin(), dom1.end(), dom2.begin(), dom2.end(), united.begin());
    cout << united.size();
    return 0;
}

如果您查看std::set_union的文档,您会发现第五个迭代器必须满足OutputIterator的要求。

然后,如果您查看std::list::begin的文档,您会发现它返回一个std::list::iterator(或std::list::const_iterator),它只是一个BidirectionalIterator,它是InputIterator的子类型。

从技术上讲,非常量InputIterator也是OutputIterator,但它的行为方式对程序不起作用。它迭代united的节点,并在已经存在的节点上复制分配源元素。但是,由于united在您的情况下是空的,迭代器超出了界限,导致了未定义的行为。

获得插入新元素的OutputIterator的一个简单方法是使用std::back_inserter

通常,每当你得到"错误和不一致的答案"时,你就会有未定义的行为,或者你的程序在没有经过诊断的情况下是错误的。寻找超出范围的错误。

这里,您的输出迭代器引用了一个不存在的范围

应该将united.begin()替换为std::back_inserter(united),以便根据需要创建元素。

这是cppreference.com std::set_union文档中的示例
阅读文档