通过地图实现树种
Tree kind implementation via map
我不想通过映射容器编写树类实现代码。
输入
> 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
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 为什么不;名字在地图上是按顺序排列的吗
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 基于多个条件处理地图中的所有元素
- 为什么地图需要实现'operator<'以及如何比较对象?
- 如何在C++的多维地图中实现常量正确性
- 通过地图实现树种
- 模板化地图/字典实现
- 打印出使用地图实现的Trie中的所有单词
- 使用C++模板实现 Haskell 的"地图"功能时出现问题
- 在C 中实现地图向量
- 如何以不同的数据类型作为值实现地图
- 田野不能被重新爱,虽然它显然在那里!(实现地图.h)
- 实现通用地图 [来自硬件]
- 如何使用范围 v3 范围实现平面地图
- 如何在将多维 int 数组映射到 C++ 中的字符串时实现在地图上查找或计数
- 如何使用Google Protobuf实现地图结构
- 你会如何实现双向地图之类的东西