c++ - 函数返回的值与 return 语句之前的函数体中的值不同
问题描述
我正在编写一个函数,该函数返回使用 kruskal 算法创建的最小生成树中两个节点之间的路径
map<string, set<string>> mst = { "A" : ["B"]
"B" : ["A", "C", "D"]
"C" : ["B"]
"D" : ["B", "E"]
"E" : ["D"] }
寻路算法如下:
vector<string> findPath(map<string, set<string>> mst, string src, string dest, vector<string> path) {
if(src == dest) {
cout << "Function path size: " << path.size() << endl;
return path;
}
set<string> possible = mst[src];
for(vector<string>::iterator it = path.begin(); it != path.end(); it++) {
if(possible.find(*it) != possible.end())
possible.erase(*it);
}
for(set<string>::iterator it = possible.begin(); it != possible.end(); it++) {
vector<string> a = path;
if(find(a.begin(), a.end(), src) == a.end())
a.push_back(src);
vector<string> p = findPath(mst, *it, dest, a);
if(p[0] != "randValue") {
return path;
}
}
vector<string> p = path;
p[0] = "randValue";
return p;
}
如果我调用该函数:
vector<string> path;
path = findPath(mst, "A", "C", path);
cout << "Main path size: " << path.size() << endl;
输出是:
Function path size: 2
Main path size: 0
为什么函数不返回填充的路径?
解决方案
我在我的函数中发现了问题,解决方案只是交换一个变量:
vector<string> findPath(map<string, set<string>> mst, string src, string dest, vector<string> path) {
if(src == dest) {
cout << "Function path size: " << path.size() << endl;
return path;
}
set<string> possible = mst[src];
for(vector<string>::iterator it = path.begin(); it != path.end(); it++) {
if(possible.find(*it) != possible.end())
possible.erase(*it);
}
for(set<string>::iterator it = possible.begin(); it != possible.end(); it++) {
vector<string> a = path;
if(find(a.begin(), a.end(), src) == a.end())
a.push_back(src);
vector<string> p = findPath(mst, *it, dest, a);
if(p[0] != "randValue") {
/**
* RETURN p INSTEAD OF path
*/
return p;
}
}
vector<string> p = path;
p[0] = "randValue";
return p;
}
推荐阅读
- json - 将 JavaScript 嵌套数组转换为启动树格式
- java - 带有 jdk11 的 Eclipse 2018-09 声称缺少 org.junit 包,即使它包含在 maven 中
- hyperledger-fabric - Hyperledger Fabric - 上传了错误的交易集。希望在链代码查询中排除这些
- java - 如何修复错误“承包商不能将上传应用到给定类型”?
- c# - 如果 boolean 为 false,则在字符串中添加逗号
- twitter - IFTTT - 排除 Twitter 转推
- javascript - 从查询字符串中检索的查询对象中查找 Mongoose
- django - django restful api - 如何序列化外键
- python - 从 cmd 运行时,pybot 未被识别为内部或外部命令
- sql - 如果我们有很多任务并且每个任务的日期范围可能重叠,如何计算任务的工作天数