gpt4 book ai didi

c++ - 使用数组时的 set_union 问题

转载 作者:行者123 更新时间:2023-11-28 02:27:29 25 4
gpt4 key购买 nike

我正在尝试使用 set_union 获取 4 个数组的并集。这是我到目前为止的代码:

int setA[5] = {2, 4, 5, 7, 8};
int setB[7] = {1, 2, 3, 4, 5, 6, 7};
int setC[5] = {2, 5, 8, 8, 15};
int setD[6] = {1, 4, 4, 6, 7, 12};

int AunionB[12];
int CunionD[11];
int finalUnion[23];

int *lastAunionB;
int *lastCunionD;

ostream_iterator<int> screen(cout, " ");

lastAunionB = set_union(setA, setA+5, setB, setB+7, AunionB);

cout << "AunionB = ";
copy(AunionB, lastAunionB, screen);
cout << endl;

lastCunionD = set_union(setC, setC+5, setD, setD+6, CunionD);

cout << "CunionD = ";
copy(CunionD, lastCunionD, screen);
cout << endl;

set_union(AunionB, AunionB+12, CunionD, CunionD+11, finalUnion);

cout << "Final Union = ";
copy(finalUnion, finalUnion+23, screen);
cout << endl;

当我运行代码时,我得到了以下输出:

AunionB = 1 2 3 4 5 6 7 8 
CunionD = 1 2 4 4 5 6 7 8 8 12 15
Final Union = 1 2 3 4 5 6 7 2 4 4 5 6 7 8 8 12 15 52187240 1 1863041424 32767 0 0

因此,setA 和 setB 的并集与 setC 和 setD 的并集一样按预期工作。但是,当我尝试获取所有集合的并集时,它不起作用!我猜 finalUnion 的最后 5 个值是地址字段,但如何删除它们?另外, union 本身是不正确的,我不明白为什么。

最佳答案

AunionB 和 Cuniond 的大小不是 12 和 11,因为:

Elements from the second range that have an equivalent element in the first range are not copied to the resulting range.

试试这段代码:

int setA[5] = { 2, 4, 5, 7, 8 };
int setB[7] = { 1, 2, 3, 4, 5, 6, 7 };
int setC[5] = { 2, 5, 8, 8, 15 };
int setD[6] = { 1, 4, 4, 6, 7, 12 };

int AunionB[12];
int CunionD[11];
int finalUnion[23];

int *lastAunionB;
int *lastCunionD;

ostream_iterator<int> screen(cout, " ");

lastAunionB = set_union(setA, setA + 5, setB, setB + 7, AunionB);

cout << "AunionB = ";
copy(AunionB, lastAunionB, screen);
cout << endl;

lastCunionD = set_union(setC, setC + 5, setD, setD + 6, CunionD);

cout << "CunionD = ";
copy(CunionD, lastCunionD, screen);
cout << endl;

int *finalUnionEnd;
finalUnionEnd = set_union(AunionB, lastAunionB, CunionD, lastCunionD, finalUnion);

cout << "Final Union = ";
copy(finalUnion, finalUnionEnd, screen);
cout << endl;

然后你得到了正确的结果:

Final Union = 1 2 3 4 4 5 6 7 8 8 12 15

关于c++ - 使用数组时的 set_union 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30036881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com