2015-06-26 108 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

相关问题