1

I know this question has sort of been asked before, but I have a specific example that I was thinking of. Currently I have a piece of code, sorta of pseudocode though, cause I'm not at my work terminal :

void setTree(string dir) {
    add dir to dirlist
    create dir object //contains list of subdirs and files
    for subdir in dir.subs do
        setTree(subdir)
    end
}

Is this possible to do with just for loops, because you can't know at compile time how many sub directories there will be at compile time. Pseudocode is fine or some explanation or algorithm. I don't really need anything because I like my recursive solution best, but I would really like to know if it is possible. As well as the theory behind it.

Taka
  • 105
  • 5
  • 1
    I'd implement it something like [this](http://stackoverflow.com/a/12569958/179910). Loki Astari's answer there is *well* worth reading as well. – Jerry Coffin Aug 04 '13 at 16:45
  • 1
    Directly below the definition of Boost.Filesystem [`recursive_directory_iterator`](http://www.boost.org/doc/libs/1_54_0/libs/filesystem/doc/reference.html#Class-recursive_directory_iterator) in its documention, there is a simplified explanation of how it works. – Benjamin Lindley Aug 04 '13 at 16:46

2 Answers2

2

For the theory see the top-voted answer here: Can every recursion be converted into iteration?

Practically:

void setTree(string dir) {
   add dir to dirlist
   while (dirlist not empty) {
   d = dirlist.pop()
   create d object
   for subdir in d.subs do
      append subdir to dirlist
   end
   }
}

I've tried to follow strange syntax mix-up of your pseudcode, hope it's still readable.

Community
  • 1
  • 1
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
  • Sorry for my odd pseudocode, too much c and Lua as of late. So we create a stack or queue sort of thing and pop and push things onto it? – Taka Aug 04 '13 at 16:39
  • No problem ;) Yes, exactly. I suppose that any typical recursion unfolded into iteration needs a collection to work in place of the stack trace holding all arguments from each recursive call. – BartoszKP Aug 04 '13 at 16:53
1

That depends on the design of the dir class. If the subdirs are saved in an array or a list there is a size-value you can use as maximum for the for-loop. That value will be defined at runtime. If the subdirs are saved otherwise you propably have to use a while-loop.

Hope it help ChronosMOT

ChronosMOT
  • 341
  • 5
  • 17