2011-10-23 38 views
0

我試圖在結構中包含一個集合,但是我不知道如何在執行此操作時將回調比較函數傳遞給set構造函數。在'struct'中包含'set'

這是什麼,我已經嘗試了基本的例子:

struct pointT { 
    int x; 
    int y; 
}; 

struct pathT{ 
    Stack<pointT> pointsInPath; 
    Set<pointT> pointsIncluded; // need callback here? 
}; 

// Tried this. 
//struct pathT{ 
    //Stack<pointT> pointsInPath; 
    //Set<pointT> pointsIncluded(ComparePoints); //doesn't work of course 
//}; 


//Callback function to compare set of points. 
int ComparePoints(pointT firstPoint, pointT secondPoint){ 

    if (firstPoint.x == secondPoint.x && firstPoint.y == secondPoint.y) return 0; 
    if (firstPoint.x < secondPoint.x) return -1; 
    else return 1; 
} 


int main() { 

    Set<pointT> setOfPoints(ComparePoints); // this works fine 
    //pathT allPaths; // not sure how to assign call back function here to a set inside a struct 

    return 0; 
} 

回答

1

你在C++中的結構自動成爲一個類。

因此你可以提供一個構造函數

struct pathT { 
    public: 
    pathT(); 

    private: 
    Stack<pointT> pointsInPath; 
    Set<pointT> pointsIncluded; 
}; 

pathT::pathT() 
: pointsIncluded(ComparePoints) 
{ 

} 

問候

4

使用自定義默認構造函數:

struct pathT{ 
    Stack<pointT> pointsInPath; 
    Set<pointT> pointsIncluded; // need callback here? 

    pathT() : pointsIncluded(ComparePoints) { } 
}; 

當你在它,移動比較成一個結構(可以內聯,不像函數指針),並將其定義爲<運算符,這是set預計的值:

struct ComparePoints { 
    bool operator()(const pointT& a, const pointT& b){ 
     return a.x < b.x || (a.x == b.x && a.y < b.y); 
    } 
}; 

struct pathT { 
    ... 
    pathT() : pointsIncluded(ComparePoints()) { } 
}; 
+0

我不知道如何實現這一點。你能提供一個簡短的例子嗎? – joeh100

+0

@ joeh100:我已經編輯了幾次我的答案,但每個版本都提供了與解釋相匹配的代碼。我不確定你還需要什麼。 –

+0

我想我在編輯之間感到困惑。也不應該你提供的第一個例子使用pointsIncluded而不是setOfPoints相同的名稱? – joeh100