我目前正在學習 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 變數中的函式回傳時間?
uj5u.com熱心網友回復:
您只是丟棄從所有呼叫回傳的值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;
這將使它回傳10.Hugo
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/519802.html
標籤:C 循环字典调试递归
上一篇:如何從字串陣列中洗掉重復的字串,但前提是它們以JS中相同的5個字符開頭?
下一篇:回圈創建多個串列,具有不同的命名
