问题是写一个A *搜索代码来逃避用C ++代码给出的迷宫。
我的代码能够编译但无法执行。当我在终端中运行它时,出现错误“分段错误(核心转储)”。任何人都可以帮我解决这个问题吗?感谢。
代码如下:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
using namespace std;
double heu(int a, int b)
{ return sqrt((a-11)*(a-11) + (b-0)*(b-0));}
class step{
public:
int x, y;
string path;
int pathcost() const {return path.length() - 1;}
double totalcost() const {return ((double) pathcost() + heu(x,y));}
bool comp(const step & , const step & ) ;
};
bool comp( const step & a, const step & b) {return (a.totalcost() < b.totalcost());}
void explore(step currentstep, char Maze[][12],vector<step> allsteps){
step tempstep;
if (( currentstep.x != 0 ) && (Maze[currentstep.x -1][currentstep.y] != '1'))
{tempstep.x = currentstep.x -1; tempstep.y = currentstep.y;
tempstep.path = currentstep.path + 'W';
allsteps.push_back(tempstep); }
if (( currentstep.x != 11 ) && (Maze[currentstep.x +1][currentstep.y] != '1'))
{ tempstep.x = currentstep.x +1; tempstep.y = currentstep.y;
tempstep.path = currentstep.path + 'E';
allsteps.push_back (tempstep);}
if (( currentstep.y != 0 ) && (Maze[currentstep.x][currentstep.y -1] != '1'))
{tempstep.x = currentstep.x; tempstep.y = currentstep.y -1;
tempstep.path = currentstep.path + 'N';
allsteps.push_back (tempstep);
}
if (( currentstep.y != 11 ) && (Maze[currentstep.x][currentstep.y +1] != '1'))
{tempstep.x = currentstep.x; tempstep.y = currentstep.y +1;
tempstep.path = currentstep.path + 'S';
allsteps.push_back (tempstep);}
}
int main()
{
string txt = "000100000000000100111111100100000000000000000000011001001101001001001000001000001000001000001000001111101011100000001000000111101000000100000000";
char Maze[12][12];
for (int i=0; i<12; i++){
for( int j =0; j<12;j++){
int k=i*12+j;
Maze[j][i]=txt[k];
}}
vector<step> allsteps;
step currentstep;
currentstep.x=0;currentstep.y=11;
currentstep.path="";
vector<step>::iterator itr;
while ((currentstep.x != 11) && (currentstep.y!=0)){
explore(currentstep, Maze,allsteps);
sort(allsteps.begin(), allsteps.end(),comp);
itr=allsteps.begin();
currentstep = *itr;}
cout<<currentstep.path;
system ("PAUSE");
}
答案 0 :(得分:1)
使用gcc编译代码我得到以下段错误信息:
#0 0x00000000004016e2 in step::operator= (this=0x7fffffffdb60) at main.cpp:13
#1 0x0000000000401468 in main () at main.cpp:73
如果我走这些路线:
currentstep = *itr;}
并且
class step{
也许它可以帮助你找到一些东西。
检查向量的内容,并打印当前的迭代。
只是一个注释
void explore(step currentstep, char Maze[][12],vector<step> allsteps)
应该是
void explore(step currentstep, char Maze[][12],vector<step>& allsteps)
编辑:当您访问
中的第一个元素时,问题是您将参数指定为值而不是引用 itr=allsteps.begin();
allsteps为空,因此*itr
将是一个无效的迭代器,并会对您的代码进行分段。
答案 1 :(得分:0)
您是否尝试过设置断点并调试代码?
cout << "this is a test line, it will print if my program gets past this point." << endl;
cin.get();
答案 2 :(得分:0)
更改您的代码以通过引用而不是按值传递所有步骤:
void explore(step currentstep, char Maze[][12],vector<step>& allsteps){
不
void explore(step currentstep, char Maze[][12],vector<step> allsteps){