stackoverflow!
For my latest assignment, I came across a problem I can't really wrap my head around.
The idea behind it is really easy, you have a basic class called Dir_or_File
, which represents (as the name suggests) a directory or a file. Every one of these has two variables within itself, it has a name
which corresponds to its path and entries
, which consists of a vector, which keeps track of all the directories or files, which are contained in my directory.
To aid in this, I have made a method called split_after_slash
, which converts any string into a vector of strings, which are split after each slash, "o1/o2/o3/" becomes a vector with the entries "o1/", "o2" and "o3". This method has been tested and it works as intended. Just for clarification, as I will be using it later on.
With this in mind, the constructor is causing problems, the idea is, that I give a path (as a string) to my constructor and it will initiate a directory.
For example:
Dir_or_File dir("/home/music/song.mp3");
Should create the Dir_or_File
object "dir", which consists of its name
, which is "/home/music/song.mp3" and a vector named entries
, which would itself contain a Dir_or_File
with the name
"home/music/song.mp3" and entries
with a Dir_or_File
with the name "music/song.mp3" in it and so on. At the end, you would have your last entry, named "song.mp3", which has an empty list of entries
.
My idea is to solve said problem via recursion, which I tried the following way:
Dir_or_File::Dir_or_File(std::string name)
{
this->name = name;
std::vector<std::string> full_path = split_after_slash(name);
if (full_path.size() > 1)
{
std::string new_param;
for (unsigned int i = 1; i < full_path.size(); i++)
{
new_param.append(full_path[i]);
}
Dir_or_File new_entry(new_param);
entries.push_back(&new_entry);
}
}
Setting the name
is self-explainatory, splitting the string should be too. After that, I only need to know if there is more than one string remaining in the path, which means I would be in a folder, which still has a sub-folder, if there is a sub-folder, I will call the constructor with everything but the folder I'm currently in, if there is no sub-folder, I don't need to add any entries to, well entries
.
But if I test my code now, I can create a Dir_or_File
, which has one entry in entries
, but thats it, the entry has no name, but some gibberish and an empty entries
vector, what am I doing wrong here?