[C++]How to use std::stack to deal with the file/directory hierarchy?

杀马特。学长 韩版系。学妹 提交于 2019-12-12 03:57:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/14867821/chow-to-use-stdstack-to-deal-with-the-file-directory-hierarchy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!