C++递归函数返回值无法累加至主函数变量的问题排查
问题
我正在学习C++,尝试实现一个递归函数:该函数读取表示金字塔结构的map<string, vector<string>>类型数据结构,通过多次递归调用自身,期望把递归返回值累加至主函数的变量中。
程序里的map<string, vector<string>>用来表示金字塔体系中领导者的关联人员,代码如下:
#include <iostream> #include <string> #include <vector> #include <map> using namespace std; int recursive_function(map<string, vector<string>> data_structure, string id) { // 遍历当前id关联的所有名字 for (auto& name : data_structure[id]) { // 当当前名字关联到主函数中声明的第一个id(Hugo)时,递归调用函数 recursive_function(data_structure, name); } // 每找到一个关联人员就返回1,预期Hugo有10个关联人员,递归总共返回11次(其中Hugo自己的返回要忽略) cout << "Now returning." << endl; // 用于调试 return 1; } int main() { // 创建表示金字塔结构的数据结构,用于导航人员间的关联关系 map<string, vector<string>> data_structure; data_structure = { {"Hugo", {"Laura", "Jasper"}}, // Hugo是领导者之一,关联Laura和Jasper {"Laura", {"Helena", "Elias"}}, {"Jasper", {"Maria", "Bibek", "Raul"}}, {"Helena", {"Sofia", "Amelia", "Rick"}}, {"Sofia", {}} }; string id = "Hugo"; int associate_counter = 0; associate_counter += recursive_function(data_structure, id); cout << "Hugo has a total of " << associate_counter - 1 // 预期输出10-1=10,但实际输出1-1=0 << " associates." << endl; return 0; }
实际运行后主函数的associate_counter无法得到预期的累加结果,请问哪里出错了?为什么没法通过递归把返回值累加到主函数的变量里?
错误原因与修复方案
核心错误
你在递归调用recursive_function(data_structure, name);时,完全没有接收并累加这个递归调用的返回值。当前代码里,每次递归调用的返回值都直接被丢弃了,只有最顶层的调用返回了1,所以associate_counter最终只会得到1,减去1后自然就是0。
另外还有个可以优化的点:每次递归都传递整个map的副本,会造成不必要的性能浪费,应该传递const引用来避免拷贝。
修复后的代码
#include <iostream> #include <string> #include <vector> #include <map> using namespace std; // 传递map的const引用,避免不必要的拷贝 int recursive_function(const map<string, vector<string>>& data_structure, string id) { int count = 1; // 先统计当前节点本身 // 遍历当前id关联的所有名字,累加每个子节点的递归结果 for (const auto& name : data_structure.at(id)) // 使用at()避免key不存在时的未定义行为 { count += recursive_function(data_structure, name); } cout << "Now returning count: " << count << endl; // 调试用,查看当前节点的统计数 return count; } int main() { map<string, vector<string>> data_structure; data_structure = { {"Hugo", {"Laura", "Jasper"}}, {"Laura", {"Helena", "Elias"}}, {"Jasper", {"Maria", "Bibek", "Raul"}}, {"Helena", {"Sofia", "Amelia", "Rick"}}, {"Sofia", {}}, // 补充缺失的节点,避免at()抛出异常 {"Elias", {}}, {"Maria", {}}, {"Bibek", {}}, {"Raul", {}}, {"Amelia", {}}, {"Rick", {}} }; string id = "Hugo"; int associate_counter = recursive_function(data_structure, id); cout << "Hugo has a total of " << associate_counter - 1 // 减去Hugo自己,得到关联人员数量 << " associates." << endl; return 0; }
修复说明
- 累加递归返回值:在循环中把每个递归调用的返回值加到
count变量里,这样每个子节点的统计数都会向上汇总,最终顶层调用返回的是包含当前节点在内的总人数。 - 传递const引用:把
map<string, vector<string>> data_structure改成const map<string, vector<string>>& data_structure,避免每次递归都拷贝整个map,提升性能。 - 处理缺失节点:原数据里
Elias、Maria等节点没有对应的条目,使用at()会抛出异常,所以补充这些空vector的节点,保证程序稳定运行。 - 明确统计逻辑:
count初始化为1,代表当前节点本身,递归累加所有子节点的数量,最终顶层返回的是Hugo加上所有关联人员的总数,减去1就是关联人员的数量。
内容的提问来源于stack exchange,提问作者lute
相关产品推荐
相关产品推荐

