﻿ c – 为什么这个函数的递归版本更快？ - 代码日志

#### c – 为什么这个函数的递归版本更快？

``````#include <array>
#include <limits>

template <int N>
class NumericRange
{
public:
//  typedef std::vector<double>::const_iterator const_iterator;
NumericRange() {
_lower.fill(std::numeric_limits<double>::quiet_NaN());
_upper.fill(std::numeric_limits<double>::quiet_NaN());
_delta.fill(std::numeric_limits<double>::quiet_NaN());
}
NumericRange(const std::array<double, N> & lower, const std::array<double, N> & upper, const std::array<double, N> & delta):
_lower(lower), _upper(upper), _delta(delta) {
_state.fill(std::numeric_limits<double>::quiet_NaN());
}

const std::array<double, N> & get_state() const {
return _state;
}

void start() {
_state = _lower;
}

bool in_range(int index_to_advance = N-1) const {
}

if ( ! in_range(index_to_advance) ) {

// carry
}
}
}

private:
std::array<double, N> _lower, _upper, _delta, _state;
};

int main() {
std::array<double, 7> lower{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
std::array<double, 7> upper{1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
std::array<double, 7> delta{0.03, 0.06, 0.03, 0.06, 0.03, 0.06, 0.03};

NumericRange<7> nr(lower, upper, delta);
int c = 0;
const std::array<double, 7> & st = nr.get_state();
++c;
}
std::cout << "took " << c << " steps" << std::endl;

return 0;
}
``````

``````void advance(int index_to_advance = 0) {
bool carry;
do {
carry = false;
if ( ! in_range(index_to_advance) ) {

// carry
carry = true;
}
}
} while (carry);
}
``````

``````void advance(int index_to_advance = 0) {

// carry
}
}
``````

``````for( ; index_to_advance < N-1 && !in_range(index_to_advance);++index_to_advance)
``````