Hiding iteration in a function
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 func开发者_高级运维tion return successive elements.
Any ideas how this could be done? thanks
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;
}
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();
}
You can use BOOST_FOREACH to simplify loops link to docs and stackoverflow
精彩评论