2011-10-23 5 views
0

私は構造体内にセットを含めることを試みていますが、これを行うときにコールバック比較関数をセットコンストラクタに渡す方法はわかりません。'構造体'の内部に 'set'を含める

これは私が試したものの基本的な例である:(あなたがそれに取り組んでいる一方で、

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

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

構造体にコンパレータを移動:

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 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

私は編集の間に混乱していると思う。また、あなたが提供した最初の例では、setOfPointsではなくpointsIncludedに同じ名前を使うべきではありませんか? – joeh100

関連する問題