我想为 std::set 设计一个自定义比较仿函数,它使用封闭类(其中定义了集合)的缓存值。
我知道在 C++ 中,没有从嵌套类到封闭类的直接访问,你需要在嵌套类中存储一个指针(关于 SO 的几个问题/答案已经很好地解释了)。
但我的问题是如何在比较仿函数中导入这样一个指针(我的代码框架中的 pModel)?
我的代码框架:
using namespace std;
class Face;
class Model
{
public:
// ...
map<Face, double> areaCached;
double area(Face f)
{
if (areaCached.find(f) == areaCached.end())
{
double calculatedValue; // perform very expensive calculation
areaCached[f] = calculatedValue;
}
return areaCached[f];
}
struct CompareByArea
{
// how can I import the pModel pointer here?
bool operator() (const Face f1, const Face f2) const
{
return pModel->area(f1) < pModel->area(f2);
}
};
set<Face, CompareByArea> sortedFaces;
};
最佳答案
不同的关联容器将比较对象作为构造函数参数。也就是说,您将添加一个指向您的比较函数的指针,并添加一个设置此指针的构造函数。然后你构造你相应的设置:
class Model {
struct CompareByArea {
Model* model;
CompareByArea(Model* model): model(model) {}
bool operator()(Face const& f1, Face const& f2) const {
return model->area(f1) < model->area(f2);
}
};
std::set<Face, CompareByArea> sortedFaces;
// ...
public:
Model(): sortedFaces(CompareByArea(this)) {}
// ...
};
this
的使用可能会在完全构造之前发出有关使用 this
的警告,但只要 this
未在CompareByArea
的构造函数访问 Model
没有问题。
关于c++ - 在 C++ 中,如何让(嵌套的)比较仿函数引用封闭类的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28721473/