#include <iostream>
#include <cmath>
#include <numeric>
#include <vector>
#include <algorithm>
bool isPointWithinSphere(std::vector<int> point, const double &radius) {
std::transform(point.begin(), point.end(), point.begin(), [](auto &x) {return std::pow(x,2);});
return std::sqrt(std::accumulate(point.begin(), point.end() + 1, 0, std::plus<int>())) <= radius;
}
int countLatticePoints(std::vector<int> &point, const double &radius, const int &dimension, int count = 0) {
for(int i = -(static_cast<int>(std::floor(radius))); i <= static_cast<int>(std::floor(radius)); i++) {
point.push_back(i);
if(point.size() == dimension){
if(isPointWithinSphere(point, radius)) count++;
}else count = countLatticePoints(point, radius, dimension, count);
point.pop_back();
}
return count;
}
MAIN
int main() {
std::vector<int> vec {};
std::cout << countLatticePoints(vec, 2.05, 2) << std::endl;
std::cout << countLatticePoints(vec, 1.5, 3) << std::endl;
std::cout << countLatticePoints(vec, 25.5, 1) << std::endl;
std::cout << countLatticePoints(vec, 2.05, 2) << std::endl;
}
上述程序运行返回以下结果:
13
19
51
9
我试图理解为什么我使用相同输入参数的第一个函数调用返回13(正确答案)作为结果,但是当我稍后再次使用相同的输入参数调用该函数时,我得到9作为答案?
想不出有什么理由会发生这种情况。
答案 0 :(得分:2)
std::accumulate
的作品来自[first,last]。这意味着它不包含last
,因此很容易阅读整个集合。您不希望使用point.end() + 1
,因为这意味着它会尝试处理point.end()
。
这样做意味着您正在向量边界之外读取并导致未定义的行为。
将行更改为
return std::sqrt(std::accumulate(point.begin(), point.end(), 0, std::plus<int>())) <= radius;