形成两组的并集似乎给出了错误且不一致的答案
Forming the union of two sets seems to give wrong and inconsistent answers
下面的代码是我试图用空集{}形成两个元素集{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
文档中的示例
阅读文档
- 递归求和任务的错误答案
- 为什么我在代码厨师的 CMPRSS 问题中得到 WA(错误答案)?
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 寻找最小楼梯成本的动态规划问题的错误答案
- 为什么可变大小的数组会导致Codechef出现错误答案
- 如何修复此代码对几个测试用例的错误答案?
- 使用幂函数的计算给出了大数字的错误答案
- 快速排序算法,一些特定输入序列的错误答案和分段错误
- 二分法程序的错误答案(C++)
- 无法理解绘图程序中的错误答案
- C++ - 整数除以整数返回错误答案
- 布尔函数的错误答案
- SPOJ FASTFLOW上的错误答案
- 代码的错误答案是在Java Camel案件和C 下划线标识符之间转换的错误答案
- 200万以下所有素数的总和,线程给出错误答案
- 0-1整数背包返回错误答案(动态编程)
- UVa 在线判断 - 3n + 1 - 错误答案
- 提升C++原始算法错误答案
- 二项式系数函数C++错误答案 n>13
- 需要帮助以避免 SPOJ 上的"错误答案"