c++ - 具有未知参数 vector 类型的虚函数

标签 c++ algorithm oop

我正在尝试用 C++ 构建优化库以进行参数优化。

问题和参数类型可能会有所不同,例如如果问题是最小化 Ackley Function , 那么我们有一个 vector<double>尺寸2 (x 的索引为 0,y 的索引为 1)。然而,当参数是整数,甚至是字符串时,我们可能会遇到问题。

很多算法都存在这种类型的优化,如遗传算法、差分进化等。在大多数算法中,一旦我们根据它们的优化策略修改参数,我们就必须调用一个接收参数的评估函数,并且给定一个目标函数,将返回一个值(适应度)。

我的问题是如何实现抽象类 Problem在 C++ 中,它包含一个 virtual double evaluate接收相关问题的通用类型 vector 作为引用的函数?比如用户的问题应该继承Problem他需要指定一个类型 T , 在这种情况下,评估函数应该像 virtual double evaluate(const vector<T> &parameters){} .

如果我上面提到的策略对 C++ 不可行。请提出替代策略。

最佳答案

根据@Quentin 的评论和您的详细信息,我会说您可以先将 Problem 声明为类模板

#include <vector>
#include <typeinfo>
#include <iostream>

using namespace std;

template<class T>
class Problem
{
public:
    Problem() {
        if(typeid(T) == typeid(double)){
            cout << "The problem is of type double" << endl;
        }
    }

    virtual double evaluate(const vector<T> &decisionVariables) = 0;
};

然后你可以从它继承并根据你的需要覆盖评估函数。既然你提到了 Ackley Function,我实现了一个 AckleyFunction,它继承自 Problem,类型为 double

#include "problem.h"
#include "math.h"

using namespace std;

class AckleyFunction : public Problem<double>
{
public:
    AckleyFunction() {}

    double evaluate(const vector<double> &decisionVariables) override {
        const double x = decisionVariables[0];
        const double y = decisionVariables[1];
        return -20 * exp(-0.2 * sqrt(0.5 * (pow(x, 2) + pow(y, 2)))) - exp(0.5 * (cos(2 * M_PI * x) + cos(2 * M_PI * y))) + exp(1) + 20;
    }
};

Ackley 函数的全局最小值是 x = 0,y = 0。您可以在 main.cpp 中看到以下内容

#include <ackleyfunction.h>
#include <memory>

using namespace std;

int main(int argc, char *argv[])
{
    shared_ptr<Problem<double>> prob(new AckleyFunction());
    vector<double> decisionVariables = {5.1, 3.3};
    cout << "Value at coordinates (5.1, 3.3): " << prob->evaluate(decisionVariables) << endl;

    decisionVariables = {0., 0.};
    cout << "Value at coordinates (0.0, 0.0): "  << prob->evaluate(decisionVariables) << endl;
}

输出:

The problem is of type double
Value at coordinates (5.1, 3.3): 12.9631
Value at coordinates (0.0, 0.0): 0

关于c++ - 具有未知参数 vector 类型的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58373116/

相关文章:

c++ - 在派生类中调用多个虚函数

c++ - 使用变量名打开文件

c++ - std:find()用于排序与未排序

javascript - 账户负天数

java私有(private)访问修饰符可以在类之外访问吗?

c++ - 装饰器模式的线程安全

c++ - 如何获取和更改 OGRE 应用程序的帧率?

c++ - 对包含结构的 std::list 进行排序

在选举中排序响应者顺序的算法

python - 如何绘制满足多个定积分的曲线?