c++ - 在 C++ 中,如何让(嵌套的)比较仿函数引用封闭类的数据?

标签 c++ caching comparator functor nested-class

我想为 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/

相关文章:

java - JTable with Comparator 在排序后访问了错误的行数据;删除 getModel() 修复了它。为什么?

c++ - 具有非成员函数的 std::vector 中的多态性

c++ - 如果在没有 new 运算符的情况下初始化,C++ 是否将类对象视为值类型?

node.js - 如何让 npm 使用缓存

c# - WCF 缓存解决方案 - 需要建议

两个 LocalDateTimes 的 java 比较器

c++ - Qt 5 让 QQuickItem 在不使用 QPainter 的情况下绘制椭圆

C++ 错误 : a brace-enclosed initializer is not allowed here before ‘{’ token

caching - Redis 在填满和逐出键时有多慢? (LRU算法)

java - 我无法弄清楚比较器