在 C++ 中定义分段函数(例如在使用样条曲线时需要)的最佳方法是什么?
Example:
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) ,我知道,也许命名不是最好的(Function
vs. std::function
等等)。
有什么想法可以以更聪明的方式做到这一点吗?该方法利用键的属性进行排序std::map
。这与效率无关,更多的是关于简洁的设计。
SLICING
不完全是问题的一部分,但在其中一条评论中,slicing提到过,您可以在这里阅读。
std::map 无法处理多态性? https://stackoverflow.com/questions/833258/stdmap-unable-to-handle-polymorphism
我在上面的代码中纠正了这个问题。