std::vector<float> spacing = ...; float point = ...; float result;
Since you say the interval is not (linear), I will cache the sums:
std::vector<float> sums(1, 0.0); float sum=0; for(int i=0; i<spacing.size(); ++i) sums.push_back(sum+=spacing[i]);
Then do a binary search to find the point on the left:
std::vector<float>::iterator iter; iter = std::lower_bound(sums.begin(), sums.end(), point);
Then find the result from there:
if (iter+1 == sums.end()) return point-*iter; else { float midpoint = (*iter + *(iter+1))/2; if (point < midpoint) result = point - *iter; else result = *(iter+1) - point; }
[EDIT] Don't feel stupid. You said that the distance was not constant. I interpreted this as non-linear. But then your code sample is linear, not a compile-time constant. To blame. I will leave this answer as a more general solution, although your (linear) question will resolve much faster.
source share