gpt4 book ai didi

c++ - 在多重映射中查找键值链的长度

转载 作者:行者123 更新时间:2023-11-28 04:07:40 25 4
gpt4 key购买 nike

我有一个网络程序,可以让用户将 2 个人添加到多 map 。关键是招聘人员,值(value)是他们增加的人,值(value)可以增加另一个人,依此类推。这是一个例子

> add john mary
> add john tom
> add mary brad
> add tom Maria
> add mary Eli
> add brad Sofia

如果我要打印 john's chain,那么我会得到以下内容。

> p john
john
..mary
....brad
......sofia
....eli
..tom
....maria

我需要找到一种方法来计算链的长度。在这种情况下,约翰链的长度为 6,玛丽的长度为 3。

这就是我打印链的方式

void print_subnet(std::multimap<std::string, std::string>networkMap, std::string id, size_t count=2)
{
for(auto itr = networkMap.begin(); itr != networkMap.end(); ++itr)
{
if(itr ->first == id)
{
std::cout << std::string(count, '.') << itr -> second << std::endl;
print_subnet(networkMap, itr->second, count+2);
}

}
}

我遵循了类似的逻辑来获得链长。

  • 对于给定的 key ,获取计数。
  • 设置key的值作为新的key
  • 重复直到 map 结束。

这是我的代码。

 int count_size(std::multimap<std::string, std::string>networkMap, std::string id, int count)
{
for(auto itr = networkMap.begin(); itr != networkMap.end(); ++itr)
{
if(itr->first == id)
{
count += networkMap.count(id);
count_size(networkMap, itr->second, count);
}
}
return count;
}

我得到的答案是 4,而它应该是 6。我打印了计数值,这就是我得到的结果。

2 (2 from john)
4 (2 from mary)
5 (1 from brad)
6 (1 from tom)
4 ??
5 ??
4 ??

我很确定我遗漏了一些简单的东西,但我已经这样做了一段时间,我无法理清思路。

最佳答案

此代码返回 6:

void count_size_recursive(std::multimap<std::string, std::string>networkMap, std::string id, int& count)
{
for(auto itr = networkMap.begin(); itr != networkMap.end(); ++itr)
{
if(itr->first == id)
{
++count;
count_size_recursive(networkMap, itr->second, count);
}
}
}

int count_size(std::multimap<std::string, std::string>networkMap, std::string id)
{
int count = 0;
count_size_recursive(networkMap, id, count);
return count;
}

关于c++ - 在多重映射中查找键值链的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58437274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com