debugging 求和递归函数将值返回给变量

yws3nbqq  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(163)

我正在学习C++,我正在尝试完成一个递归函数,它首先读取一个数据结构,然后将自己返回给主函数n次。这些返回值应该在主函数中求和,并赋给一个变量。
在我的程序中,我有一个更复杂的数据结构,它是一个Map,由字符串和一个向量字符串组成,这个数据结构的目的是显示金字塔计划:所有与金字塔计划领导人有关的人。

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;

int recursive_function(map<string, vector<string>> data_structure, string id)
{
    // Going trough every name associated with the current id-name.
    for (auto& name : data_structure[id])
    {
        // Recalling the function, when the current name is associated to the
        // first name-id declared in the main function (Hugo).
        recursive_function(data_structure, name);
    }

    // Returning the function, every time a single associate has been found.
    // In this case, we get 10 associates with Hugo, which means the recursive
    // function will be returned a total of 11 times (1 of these returns will be
    // ignored, since Hugo can't be an associate with himself in the example...

    cout << "Now returning." << endl; // This is just for clarity.
    return 1;

}

int main()
{
    // Creating the data-structure, which displays a pyramid scheme. It can be
    // used to navigate trough connections between the people.
    map<string, vector<string>> data_structure;
    data_structure = {
        {"Hugo", {"Laura", "Jasper"}}, // Hugo is one of the leaders. He is
                                       // associated with Laura and Jasper, who
                                       // are associated with others etc. Laura
                                       // and Jasper too are one of the leaders.
        {"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   // Should print the equation 10-1 (10), but
         << " associates."          // instead, prints 1-1 (0).
         << endl;

    return 0;
}

我做错了什么?为什么我不能用递归的方法,在主函数associate_counter变量中计算函数返回时间的总和?

2skhul33

2skhul331#

您只是丢弃了所有recursive_function调用返回的值,需要将它们相加。
示例:

int sum = 0;
for (auto& name : data_structure[id])
{
    sum += 1 + recursive_function(data_structure, name);
    // + 1 for the associate
    // + the sum of the associate's associates (recursively)
}
return sum;

这将使它返回Hugo10
Demo

相关问题