0

Only got rough idea of what I want, perhaps someone could pad it out and/or tell me if its possible.

I would like to simplify my multiply nested loops, to that end I would like to be able to call a function (for example that uses boost::filesystem) that returns a file in a directory, each successive call would return the next file, until all were exhausted. Also i would like to be able to do this with a vector, and have the function return successive elements.

Any ideas how this could be done? thanks

pingu
  • 8,719
  • 12
  • 50
  • 84
  • 4
    It sounds like you're trying to re-invent iterators. Iterators are a fairly normal way of working with `std::vector`. `boost::filesystem` has a `directory_iterator` as well. – Jerry Coffin Mar 14 '11 at 23:05
  • @Jerry - I am using iterators for both Vectors and filesystem, but i am wanting to avoid the nested iterator loops, as they are 10 deep and disappear off the right of your screen. – pingu Mar 15 '11 at 07:49

3 Answers3

1

use Iterator pattern. In Java you'd have smth like this:

class FileIterator {
  private int index;
  private File[] files;

  public FileIterator(File[] files) {
    this.files = files;
    this.index = 0;
  }

  public boolean hasNext() {
    if (index < files.length - 1) { 
      return true;
    } else {
      return false;
    }
  }
  public File next() {
    return this.files [index ++];
  }
}

and you'd use it like this:

FileIterator it = new FileIterator(theFiles);
while (it.hasNext()) {
  File f = it.next();
}
iluxa
  • 6,941
  • 18
  • 36
1

Create a functor: an object that is called like a function.

The object will hold the query results and the current state of the query. You define an operator() so the object can be called as if it were a function. Each time this function is called you return one result and update the object's internal state.

Example:

#include <iostream>

using namespace std;

class CountDown {
        unsigned count;
public:
        CountDown(unsigned count) : count(count) {}
        bool operator()() { return count-- > 0; }
};

int main()
{
        CountDown cd(5);
        while( cd() ) {
                cout << "Counting" << endl;
        }
        return 0;
}
Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
1

You can use BOOST_FOREACH to simplify loops link to docs and stackoverflow

Community
  • 1
  • 1
Gregor Brandt
  • 7,659
  • 38
  • 59