3

たとえば、スプラインを操作するときに必要な、C++ で区分関数を定義する最良の方法は何ですか?

例:

        f1(x) if x from [0, 5)
f(x) =  f2(x) if x from [5, 10)
        f3(x) if x from [10, 20)

私の現在のアプローチは次のようになります。

class Function
{
    virtual double operator()( double x ) = 0;
}

class SomeFun : public Function
{
   // implements operator() in a meaningful way
}

class PiecewiseFunction : public Function
{
    // holds functions along with the upper bound of the interval
    // for which they are defined
    // e.g. (5, f1), (10, f2), (20, f3)
    std::map< double, Function* > fns;

    virtual double operator()( double x )
    {
       // search for the first upper interval boundary which is greater than x
       auto it = fns.lower_bound( x );
       // ... and evaluate the underlying function.
       return *(it->second)(x);
    }
}

xこのアプローチでは、上記の例の [0, 20) のように、関数の全体的な境界内にあるかどうかのチェックが欠けており、おそらく命名が最適ではありません ( Functionvs.std::functionなど)。

よりスマートな方法でそれを行う方法はありますか? このアプローチでは、キーのプロパティを使用して、std::map. 効率ではなく、クリーンなデザインが重要です。

スライス

正確には質問の一部ではありませんが、コメントの 1 つで、スライスについて言及されています。ここでそれについて読むことができます。

std::map はポリモーフィズムを処理できませんか?

上記のコードでこれを修正しました。

4

1 に答える 1