我遇到的问题是我需要使用copy函数从union_set函数打印结果集。 (所以我不允许将输出作为set_union函数的最后一项)。我似乎无法让copy函数正确地为lastAunionB指针工作(我还需要几次)。我目前所拥有的只是我最后一次尝试答案,尽管我尝试了更多的东西。我对复制功能做错了什么?这是代码。
#include <iostream>
#include <iterator>
#include <set>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
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};
set<int> set2A(setA,setA+5);
set<int> set2B(setB,setB+7);
set<int> set2C(setC,setC+5);
set<int> set2D(setD,setD+6);
int AunionB[12];
int AunionC[10];
int BunionD[13];
int AintersectB[12];
int AintersectC[10];
set<int> finalUnion;
set<int> finalIntersection;
set<int> final2Union;
set<int> final2Intersection;
set<int> final2Difference;
ostream_iterator< int > output( cout, " " );
int *lastAunionB;
int *lastAunionC;
int *lastBunionD;
int *lastAintersectB;
int *lastAintersectC;
cout << "setA = ";
copy(set2A.begin(), set2A.end(), output);
cout << endl;
cout << "setB = ";
copy(set2B.begin(), set2B.end(), output);
cout << endl;
cout << "setC = ";
copy(set2C.begin(), set2C.end(), output);
cout << endl;
cout << "setD = ";
copy(set2D.begin(), set2D.end(), output);
cout << endl;
//here is where the problem lies
cout << "AunionB = ";
lastAunionB = set_union(setA, setA+5, setB, setB+7, AunionB);
copy(lastAunionB, lastAunionB, output);
cout << endl;
/*
cout << "AunionC = ";
set_union(setA, setA+5, setC, setC+5, AunionC);
cout << endl;
cout << "BunionD = ";
set_union(setB, setB+7, setD, setD+6, BunionD);
cout << endl;
cout << "AintercectB = ";
set_intersection(setA, setA+5, setB, setB+7, AintersectB);
cout << endl;
cout << "AintercectC = ";
set_intersection(setA, setA+5, setC, setC+7, AintersectC);
cout << endl;
*/
return 0;
}
答案 0 :(得分:1)
lastAunionB = set_union(setA, setA+5, setB, setB+7, AunionB);
copy(lastAunionB, lastAunionB, output);
传递给set_union
的最后一个参数将对应于构建的新集合范围的开头。 set_union
的返回值将是此范围的结尾。
你想要lastAunionB
和其他原始指针以及你作为迭代器传递的几乎所有内容都是用类型std::set<int>::iterator
定义的,并且你想要复制范围像这样:
std::copy(AunionB, lastAunionB, output);
答案 1 :(得分:0)
您正试图从空范围内复制。
copy(ptr,ptr,output);
永远不会打印任何内容。