包括'struct'内部的'set'

Including a 'set' inside of a 'struct'

本文关键字:set struct 包括 内部      更新时间:2023-10-16

我试图包括一个集合,内部结构,但我不知道如何传递回调比较函数到集构造函数时这样做。

这是我尝试过的一个基本例子:

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

使用自定义默认构造函数:

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()) { }
};

c++中的结构体自动成为一个类。

因此可以提供构造函数

struct pathT {
    public:
    pathT();
    private:
    Stack<pointT> pointsInPath;
    Set<pointT> pointsIncluded; 
};
pathT::pathT()
: pointsIncluded(ComparePoints)
{
}