[C ++]如何使用std :: stack处理文件/目录层次结构? [英] [C++]How to use std::stack to deal with the file/directory hierarchy?

查看:180
本文介绍了[C ++]如何使用std :: stack处理文件/目录层次结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个类,Root,CFile,SubDirectory。 Root是一个抽象类。 CFile和SubDirectory是从根派生的。 CFile有属性:name:string,size:int,level:int。 SubDirectory有属性:name:string,size:int,level:int,一个向量,它包含文件和目录,还有一个函数void add()将文件或目录推入向量。如果一个文件在一个目录中,文件的级别比目录的高一级。现在,我有一个名为DirRead.h的文件,它可以构造当前目录(计算机文件夹)中的所有条目。每个条目都有文件名,大小,级别和类型(文件或目录)。在主函数中,我被要求使用DirRead的信息作为输入来构造文件系统的层次结构(使用CFile和SubDirectory)。 DirRead.h进行预订triversal。在这种情况下不接受递归(我尝试,并且DirRead.h报告错误)。我被要求使用堆栈来处理输入,但我不知道如何。显然水平在这里真的很重要。我试图创建一个堆栈,将所有的文件和目录推入堆栈,然后比较级别以形成层次结构。但是Root没有Add函数,没有办法将CFile添加到SubDirectory,因为它们都是Root *。任何人都知道如何做到这一点? Thx。

解决方案

您使用堆栈来跟踪您尚未探索的目录。您可以使用以下算法:


  1. 将根目录推入堆栈。


  2. 从堆栈中弹出顶层条目。


  3. 遍历您从堆栈中取出的目录。将其中的每个文件和目录添加到数据结构中。


  4. 转到第2步。



I have 3 class, Root, CFile, SubDirectory. Root is a abstract class. CFile and SubDirectory are derived from Root. CFile has attributes: name:string , size:int, level:int. SubDirectory has attributes: name:string, size:int, level:int,a vector, which contains both files and directories and a function void add() to push the file or directory into the vector. If a file in a directory, file's level is higher than the directory's by one. All setters and getters are defined.

Now, I have a file called DirRead.h that can struct all the entries in the current diretory (computer's folder). Each entry has a filename, size, level and type (either File or Directory). In the main function, I'm asked to use the information from DirRead as input to construct the hierarchy of file system (using CFile and SubDirectory). DirRead.h conducts pre-order triversal. Recursion is not accepted in this case (I tried, and DirRead.h reported error). I'm asked to use stack to deal with the input, but I don't know how. Apparently level is really important here. I have tried to create a stack and push all the files and directories into the stack, then compare the level to form the hierarchy. But Root doesn't have Add function, there's no way to add CFile into SubDirectory because they are all Root*. Anyone knows how to do this? Thx.

解决方案

You use the stack to keep track of directories you haven't explored yet. You can use the following algorithm:

  1. Push the root directory onto the stack.

  2. Pop the top entry off the stack. If the stack is empty, stop, you're done.

  3. Traverse the directory you pulled off the stack. Add every file and directory in it into your data structure. Also, push every directory you find onto your stack.

  4. Go to step 2.

这篇关于[C ++]如何使用std :: stack处理文件/目录层次结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆