简体   繁体   中英

C++ Horner's Rule - Recursive Array Implementation

I've implemented the Horner's Method using arrays as follows.

double hornerRule( const double x, const double a[], const int n ) {
    double ans = *a;
    if ( n > 0 ) { ans += x * hornerFunction( x, ++a, n - 1 ); }
    return ans;
}

I'm a bit new to the pointer arithmetic and have a few questions:

  1. Did I commit any sins? Is there a better way to do it?
  2. An analogous implementation uses std::vector and avoids passing the array size n . What are the pros/cons of these two implementations?

With a new C++ compiler the modern way would be to have a std::span or gsl::span parameter. It contains the pointer and the length, sub-arrays can be built from it easily.

Depending on n, it could improve the performance, if you change n to a template parameter. Then the recursion could be unrolled without problems and the compiler could do its optimization magic.

You could do the unrolling by manuelly convertig to a loop, too.

It all depends on your aims. Should the function just work correctly. Or is it performance-critical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM