C ++使用继承来调整算法 [英] C++ Using inheritance to tweak an algorithm

查看:49
本文介绍了C ++使用继承来调整算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Dijkstra的算法和Prim的算法是如此相似,我想创建一个基本的算法类(我称其为"Greedy"之类),然后我想从Greedy继承并基于课.

Since Dijkstra's algorithm and Prim's algorithm are so similar, I'd like to make a base algorithm class (I'll call it "Greedy" or something) and then I want to inherit from Greedy and tweak the algorithm based on the class.

我认为可以归结为这一点.我想重用算法的很大一部分,但要调整一两个操作.

I think it boils down to this. I'd like to reuse a large portion of an algorithm but tweak an operation or two.

class BaseAlg
{
public:
    BaseAlg(std::vector<int> data)  //constructor sums a vector and stores result
    {
        int accum = 0;
        for (unsigned int i = 0; i < data.size(); ++i)
            accum += data[i];
        result = accum;
    }

protected:
    int result;
};

class Alg1  //A second, similar algorithm
{
public:
    Alg1(std::vector<int> data)
    {
        //I want to reuse BaseAlg except use *= instead of +=; 
    }
};

因此,执行此操作的一种方法是仅拥有一个类(BaseAlg),并向该类的构造函数添加选择器"值.我将打开该选择器值,并在不同情况下执行+ =或* =.我觉得应该有一种通过继承来实现这种重用的方法,因为贪婪与Prim和贪婪与Dijkstra之间存在一种是"关系.但我不太清楚.有什么想法吗?

So one way to do this is to only have one class (BaseAlg) and to add a "Selector" value to the class's constructor. I would switch on that selector value and execute += or *= in different cases. I feel like there should be a way to implement this reuse with inheritance because there is an "is a" relationship between Greedy and Prim and Greedy and Dijkstra. But I can't quite figure it out. Any thoughts?

推荐答案

对于这种重用但也不是真正的继承",您应该使用模板.

You should use templates for this kind of "reuse but nor really inheritance".

例如,在您的情况下,基本上可以归结为:

For instance, in your case, basically it boils down to this:

template<class Op, class Iter, class T> T reduce(const Op & op, Iter begin, Iter end, T init = T()) {
    T accum = init;
    for(Iter i = begin; i != end; ++i)
        accum = Op(accum, *i);
    return accum;
}

然后您可以像这样使用它:

You could then use it like this:

std::vector<int> data; // fill data
int sum = reduce(add<int>, data.begin(), data.end());
int prod = reduce(mul<int>, data.begin(), data.end(), 1);

您需要在其中定义 add mult 的位置,

where you'd need to define add and mult like this:

template<class T> T add(T a, T b) { return a + b; }
template<class T> T mult(T a, T b) { return a * b; }

现在,这一切都是出于说明目的,正如Jerry Coffin所指出的那样,使用STL,您可以轻松做到:

Now, this was all for illustrative purpose, as Jerry Coffin pointed out, with the STL you can simply do:

#include <functional>
#include <numeric>
int sum = std::accumulate(data.begin(), data.end(), 0, std::plus<int>);

这篇关于C ++使用继承来调整算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆