我试图在结构中包含一个集合,但我不知道如何在执行此操作时将回调比较函数传递给集合构造函数。
这是我尝试过的一个基本示例:
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/