这段代码应该可以完美运行并给出正确的结果,但事实并非如此。我用了调试器,一切正常。 c.i
和 c.j
在函数返回之前具有正确的值。我确保在开始和结束之间总是有一条路径,所以这不是问题。 path
和 vis
数组也填充了正确的值。所以唯一的问题是它何时返回。它给出随机的大数字。只有当我在函数末尾放置一个 return 语句时它才有效。但是我可以创建一个函数,只在 if
子句中放置一个 return 语句并且它可以工作。是否存在某种规则,函数末尾必须有任何类型的 return 语句?为了测试它,我输入了 3x3 二维数组和 1。有什么解决办法吗?
编辑:我在 ideone
上运行它,它在函数末尾没有 return 语句的情况下工作。我的一个 friend 也在他的电脑上测试过它也有效。我在 Windows 7 上使用代码块。可能是什么问题?
#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <cmath>
using namespace std;
struct crd {
int i,j;
};
bool vis[50][50];
int map[50][50];
int path[50][50];
int di[4] = {1,-1,0,0};
int dj[4] = {0,0,1,-1};
int bfs(crd start, crd end, int n, int m)
{
queue<crd> q;
crd t,c;
q.push(start);
vis[start.i][start.j] = 1;
path[start.i][start.j] = 0;
while (!q.empty()) {
t = q.front();
q.pop();
for (int i=0; i<4; i++) {
c.i = t.i + di[i];
c.j = t.j + dj[i];
if (c.i >= 0 && c.j >= 0 && c.i < n && c.j < m) {
if (map[c.i][c.j] != -1 && vis[c.i][c.j] != 1) {
q.push(c);
vis[c.i][c.j] = 1;
path[c.i][c.j] = path[t.i][t.j] + 1;
if (c.i == end.i && c.j == end.j)
return path[end.i][end.j];
}
}
}
}
// if i put this: return path[end.i][end.j]; it works
}
int main()
{
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++)
cin >> map[i][j];
}
crd s,e;
s.i = s.j = 0;
e.i = e.j = 2;
int sp = bfs(s,e,3,3);
cout << sp << endl;
return 0;
}
最佳答案
编译器非常基础 - 它无法知道您的函数将始终在您的 if
中返回,在 if
中,在另一个 if< 中
在 while
循环内的 for
循环内。所以它警告你你可能不会从函数返回任何东西。最简单的解决方法是在最后返回适当的值,并且只在您现在返回的那一点跳出循环。
关于c++ - 控制到达非 void 函数的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957919/