通过地图实现树种

Tree kind implementation via map

本文关键字:实现 地图      更新时间:2023-10-16

我不想通过映射容器编写树类实现代码。

输入

> S Hugo Laura
> S Hugo Jasper
> S Laura Helena
> S Jasper Maria
> S Laura Elias
> S Helena Sofia
> P Hugo

输出

Hugo
..Laura
....Helena
......Sofia
....Elias
..Jasper
....Maria

我已经有了将雨果和劳拉拆分为变量的拆分函数。但是我应该如何通过地图容器实现输出种类的结果。我应该在地图的地图中使用某种递归或地图,这对我来说听起来很奇怪(无尽的地图(。提前谢谢。

这是一个可能的解决方案,使用 multimap .您不必复制它,但可以随意使用它作为示例来制作自己的。Multimap允许有重复的键,你可以用equal_range方法查询。通过使用映射值作为下一个节点,结合递归函数可以产生所需的确切结果:

#include <iostream>
#include <string>
#include <map>
void explore (std::multimap<std::string, std::string> const &tree, std::string const &key, int level) 
{
    level+=2;
    auto range = tree.equal_range(key);
    for (auto it = range.first; it != range.second; ++it)
    {
        std::cout << std::string(level, '.') << it->second << std::endl;
        explore(tree, it->second, level);
    }
}
int main()
{
    std::multimap<std::string, std::string> tree = 
    {
        { "Hugo", "Laura" },
        { "Hugo", "Jasper" },
        { "Laura", "Helena" },
        { "Jasper", "Maria" },
        { "Laura", "Elias" },
        { "Helena", "Sofia" }
    };
    std::string root = "Hugo";
    std::cout << root << std::endl;
    explore(tree, root, 0);
    return 0;
}

https://ideone.com/HywQo9