2015-06-26 107 views
2

我想寫一個助推算法(人工智能的一個功能)。速度是一個優先事項,所以我從使用我的本地Python切換到C++。我編寫了整個程序,但是我得到了一個缺陷,我減少了我在基類中犯的一個錯誤:一個非常簡單的啓發式稱爲「H」。該文件HH,h.cpp,和我目前的測試功能的main.cpp是:爲什麼這個看似簡單的C++代碼會產生分段錯誤?

//h.h 

#ifndef __H_H_INCLUDED__ 
#define __H_H_INCLUDED__ 

#include <iostream> 
#include <vector> 

class H 
{ 
    public: 
     H(int, double, bool); 
     //The first parameter is the axis 
     //The second parameter is the cutoff 
     //The third parameter is the direction 
     bool evaluate(std::vector<double>&); 
     //This evaluates the heuristic at a given point. 
    private: 
     int axis; 
     double cutoff; 
     bool direction; 
}; 

#endif 

//h.cpp 

#include "h.h" 

H::H(int ax, double cut, bool d) 
{ 
    axis = ax; 
    cutoff = cut; 
    direction = d; 
} 

bool H::evaluate(std::vector<double>& point) 
{ 
    if (direction) 
    { 
     return point[axis] > cutoff; 
    } 
    else 
    { 
     return point[axis] <= cutoff; 
    } 
} 

//main.cpp 

#include <iostream> 
#include <vector> 
#include "h.h" 

int main() 
{ 
    H h(0, 2.0, true); 
    for (double x = 0; x < 4; x = x + 1) 
    { 
     for (double y = 0; y < 4; y = y + 1) 
     { 
      std::vector<double> point(x, y); 
      std::vector<double>& point_ref = point; 
      std::cout << "Before computation" << std::endl; 
      bool value = h.evaluate(point_ref); 
      std::cout << "After computation" << std::endl; 
      std::cout << "heuristic(x = " << x << ", y = " << y << ") = " << value << std::endl; 
     } 
    } 
    return 0; 
} 

(我把「計算之前」和「之後計算」在查明這行中出現的錯誤。)相當與我期望的輸出相反,我得到:

Before computation 
Segmentation fault (core dumped) 

我做錯了什麼?那個錯誤信息甚至意味着什麼?
謝謝!

編輯:我使用C++ 11,只是爲了好奇的人。

+2

您的載體'point'是空的。將x和y推回給它。 – Tempux

回答

6

這條線:

std::vector<double> point(x, y); 

使得y一個vectorx副本。這是constructor #2 here。所以當x爲0時,point是空的vector - 這意味着您訪問索引爲0的元素是未定義的行爲,在這種情況下由分段錯誤表示。

什麼你可能本來打算做的是使包含兩個值xy,這將是一個向量:

std::vector<double> point{x, y}; // in c++11, note the braces 

std::vector<double> point(2); // pre-c++11 
point[0] = x; 
point[1] = y; 
+0

謝謝!完美的作品 – QuantumFool

相關問題