c++ - 在 'set' 中包含一个 'struct'

标签 c++ callback 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;
}

最佳答案

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

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++ - 在 'set' 中包含一个 'struct',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7869102/

相关文章:

c++ - C++如何从文件夹中获取文件名

c++ - 为什么我的类析构函数会立即被调用?

c++ - 在 C++ 中,将静态成员函数指针用于 C API 回调是否安全/可移植?

javascript - 如何避免在 promise 回调中包装代码?

c++ - 如何使用 C++ 在 OSX 中获取当前用户的语言环境

c++ - std::stringstream(设置failbit和badbit的方法)中可能存在哪些错误?

python - 在 Python 中实现回调 - 将可调用引用传递给当前函数

c - 在结构数组上使用 realloc

c++ - 结构和类错误

python - 在Python中解压ripemd160结果