2016-05-20 32 views
0
#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が得られますか?

これは何らかの理由で発生するとは考えられません。

答えて

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; 
に行
関連する問題