2013-07-21 92 views
0

我遇到的問題是我需要使用複製功能從union_set函數打印結果集。 (所以我不允許把輸出作爲set_union函數的最後一項)。我似乎無法讓複製函數爲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; 

}

回答

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); 
0

你試圖從一個空的範圍內複製。

copy(ptr,ptr,output); 

將永遠不會打印任何東西。