I have written a very simple file managing database that basicly looks like this:
class FileDB
{
public:
FileDB(std::string dir) : rootDir(dir) { }
void loadFile(std::string filename, File &file) const;
void saveFile(std::string filename, const File &file) const;
private:
std::string rootDir;
}
Now I would like to iterate through all files contained in the database like using a std::iterator:
void iterateFiles()
{
FileDB filedb("C:\\MyFiles");
for (FileDB::iterator file_it = filedb.begin(); file_it != filedb.end(); ++file_it)
{
File f = *file_it;
// do something with file
}
}
I’ve read answers to similar questions, some suggesting to derive std::iterator, some to use std::iterator_traits, but I don’t really understand how to do that. What can possibly go wrong when trying to implement a custom iterator? And what’s a simple yet elegant way to do it?
EDIT:
Please don’t consider using boost, my question is of more conceptual nature.
EDIT 2:
The FileDB works like this:
-
rootDir
- foo1
- bar1
- foo1bar1_1.txt
- foo1bar1_2.txt
- bar2
- foo1bar2_1.txt
- foo1bar2_2.txt
- bar1
-
foo2
-
fooN
-
barM
- fooNBarM_x.txt
-
- foo1
So basicly, I can find a file by its name.
As my container is not in memory, I don’t have pointers to its data. So my idea was to store the file’s path in the iterator. This way, I can implement operator== with a string comparison, as the paths should be unique. The iterator returned from fileDB.end() would be an empty string and operator* would call fileDB::loadFile() with its filepath.
My biggest concern is about operator++. Having the filename, I can find out the containing directory and search for the next file, but this is really ineffective. Any ideas on how to do that? Or am I completely wrong with my whole concept?
1 Answer