C++ 路径树到树结构
假设您有普通的unix路径树作为输入(作为字符串) 将此字符串转换为树数据结构的更好方法是什么?类似以下内容: 为“\”创建根节点C++ 路径树到树结构,c++,algorithm,tree,C++,Algorithm,Tree,假设您有普通的unix路径树作为输入(作为字符串) 将此字符串转换为树数据结构的更好方法是什么?类似以下内容: 为“\”创建根节点 node=root; token=getNextToken(inputString); while (token){ if (!node.childExist(token)) node.createChild(token) node=node.Child(token) token=getNextToken(inputString); } 现在我使用自己创建的
node=root;
token=getNextToken(inputString);
while (token){
if (!node.childExist(token)) node.createChild(token)
node=node.Child(token)
token=getNextToken(inputString);
}
现在我使用自己创建的简单树表示法
template<typename T>
class TreeNode
{
public:
TreeNode() {};
TreeNode(T)
{
value = T;
}
TreeNode(const T& value)
: Value(value)
{
}
T Value;
vector<TreeNode<T>*> Children;
};
对我来说,这个算法似乎非常复杂。我不明白上面贴的算法,也许可以澄清这个问题?也许我用来存储树的结构不是最好的?Q:你是什么意思?另外:看这里:我有路径树作为字符串。我需要生成树数据结构(c++类)并反映适当的层次结构。我认为没有最好的方法。您只需定义树结构并解析文件。这是正常的编程工作,换句话说,没有技巧。没有“更好”的方法。如果您想要一个类似于树的文件系统,那么您需要一个类似于虚拟文件系统的东西。或者您可以编写一个函数,一次添加完整路径。您可能应该首先使用std::map.Yup——这绝对是解析字符串以构建树的好算法。下一个问题是“我用什么来实现树?”这就是我上面引用的链接的来源:。正如贾哈吉所说,没有现成的内置“最佳方式”。吉尔:不允许使用任何第三方图书馆。代码中的节点是什么?Ipaulsm4:我看到了这个链接,但我不能使用boost图形库来解决这个问题。你不需要任何第三方库,你可以自己编写一个树类
template<typename T>
class TreeNode
{
public:
TreeNode() {};
TreeNode(T)
{
value = T;
}
TreeNode(const T& value)
: Value(value)
{
}
T Value;
vector<TreeNode<T>*> Children;
};
1. Get a root node, set depth_level = 0
3. set support_node = root_node
4. for each path line
5. determine the quantity of slashes "/", key and file(folder) name
so for example in string root/folder1/file4.txt 5, num of slashes = 2 filename = file4.txt, key = 5
create current_node
6. if num_of_slashes == level + 2
7. set support_node = current_node
8. if num_of_slashes == level + 1
9. add children to support_node
10. And after that we must remember all ancestors, going down to leaves. Cuz we can return to any ancestor.