我从一个 xml 文件中提取了父子关系。唯一的假设是 ROOT 是父节点。其余的节点到处都是。示例数据集如下所示:
PARENT | CHILD
DEL | 4568
ZPER | CF00
D034 | SDCX
ROOT | L3NP
D034 | SLGH
L3NP | AZQW
DEL | 31SW
ROOT | D034
SLGH | DFGT
L3NP | ZPER
DEL | DFRT
ROOT | DEL
我将这些数据存储在一个向量中:
struct t{
string p; /* parent */
string c; /* child, child can be a parent of another node */
};
vector<t> tree;
tree.push_back(t());
tree[tcntr].p=prnt;
tree[tcntr].c=chld;
我不确定如何跟踪找到每个成员的级别。也许有一种标准方法可以尝试生成我不知道的层次结构,希望能帮我指明正确的方向。
最后输出应该是这样的:
ROOT
> L3NP
> AZQW
> ZPER
> CF00
> D034
> SDCX
> SLGH
> DFGT
> DEL
> 4568
> 31SW
> DFRT
答案 0 :(得分:0)
这可以通过递归函数来完成。我不知道您如何存储您显示的值,但我们可以使用 std::unordered_multimap
:
#include <stdio.h>
#include <string>
#include <unordered_map>
#include <vector>
using Map = std::unordered_multimap<std::string, std::string>;
struct Node {
std::string name = {};
std::vector<Node> children = {};
};
Node MakeTree(Map const& map, std::string const& nodeName) {
Node node{nodeName};
auto const rng = map.equal_range(nodeName);
for (auto it = rng.first; it != rng.second; ++it)
node.children.push_back(MakeTree(map, it->second));
return node;
}
void Print(Node const& n, unsigned lvl = 0) {
printf("%*c %s\n", lvl * 2, '>', n.name.c_str());
for (auto const& child : n.children)
Print(child, lvl + 1);
}
int main() {
Map const map = {
{"DEL", "4568"}, {"ZPER", "CF00"}, {"D034", "SDCX"}, {"ROOT", "L3NP"},
{"D034", "SLGH"}, {"L3NP", "AZQW"}, {"DEL", "31SW"}, {"ROOT", "D034"},
{"SLGH", "DFGT"}, {"L3NP", "ZPER"}, {"DEL", "DFRT"}, {"ROOT", "DEL"},
};
Node const tree = MakeTree(map, "ROOT");
Print(tree);
}
输出:
> ROOT
> L3NP
> AZQW
> ZPER
> CF00
> D034
> SDCX
> SLGH
> DFGT
> DEL
> 4568
> 31SW
> DFRT