Notice: Undefined offset: 6902316 in /var/www/html/qa-external/qa-external-users.php on line 744

Notice: Undefined offset: 16522551 in /var/www/html/qa-external/qa-external-users.php on line 744
C++ looking for an alternative for this code that isnt repetitive. - OnlineGDB Q&A
Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

C++ looking for an alternative for this code that isnt repetitive.

+23 votes
asked Aug 31, 2025 by (6,150 points)

Hello There! I am *back*. I haven't been on this platform for quite a while now, but nothing has changed i see

So, I am making a CLI Terminal project in C++ (full code at https://www.github.com/PCPPTech/-F00L.)

```

for(const string& element : folders_withDot)

    inorder.push_back(element);

  for(const string& element : folders)

    inorder.push_back(element);

  for(const string& element : files_withDot)

    inorder.push_back(element);

  for(const string& element : files)

    inorder.push_back(element);
```

here, I iterate thru all the previous string vectors
Here is the code before that:
```

vector<string> folders_withDot, folders, files_withDot, files, inorder; // creating every list where we will store certain stuff in 1 line

  for(const auto& entry : fs::directory_iterator(path)) { // iterate thru the given path

    string filename = entry.path().filename().string(); // This is our readable filename

    // first = Folders starting with .

    if (filename.starts_with(".") && fs::is_directory(entry.path())) // if it starts with a dot and is a directory

      folders_withDot.push_back(filename);                           // then it belongs in the folder_withDot string vector.

    // second = Ordinary Folders (not starting with .)

    if (fs::is_directory(entry.path()) && !(filename.starts_with("."))) // if it is a directory and it doesn't start with a dot

      folders.push_back(filename);                                      // then it belongs in the normal folders string vector

   

    // third = Files starting with a .

    if (!(fs::is_directory(entry.path())) && filename.starts_with(".")) // if it isn't a directory but does start with a dot

      files_withDot.push_back(filename);                                // then it belongs in the files_withDot string vector

    // fourth = files that dont start with a dot.

    if (!(fs::is_directory(entry.path())) && !(filename.starts_with("."))) // if it isn't a directory and it doesnt start with a dot

      files.push_back(filename);                                           // then it belongs in the normal files string vector.

    // iterate thru each one... this is gonna be so so so slow...

    // idk how to iterate thru 4 arrays in 1 for loop without knowing their length for sure

  }
```
I tried to comment everything thoroughly.
So I iterated thru all the sorted string vectors and put them inorder in the string vector `inorder`.

So, my problem is that the first code i provided is really repetitive and I think there is a better way to do it. Maybe nested loops? I dont know.

If you have an idea, Please share it here, I appreciate it! ^^

5 Answers

+3 votes
answered Sep 1, 2025 by Peter Minarik (101,340 points)
selected Sep 1, 2025 by
 
Best answer

iterate thru each one... this is gonna be so so so slow...

Is it actually slow? Have you done any measurements on how long it takes to run through that piece of code? Have you done a performance analysis to find out why it is slow? What part of the code makes it slow?

You have to iterate through the files anyway; you cannot avoid that. What you could avoid is doing the same thing multiple times.

E.g. fs::is_directory(entry.path()) is called 4 times. You could just store it in a variable inside your loop once, and not evaluate this expression 4 times in your code.

Same for filename.starts_with(".").

Anything that you use multiple times could be stored in a variable.

Something like this (I haven't made sure the code compiles, though!)

    for(const auto& entry : fs::directory_iterator(path))
    {
        // Cached values as they will be used multiple times
        auto path = entry.path();
        string filename = path.filename().string();
        bool startsWithDot = filename.starts_with(".");
        bool isDirectory = fs::is_directory(path);

        if (isDirectory)
        {
            if (startsWithDot)
                folders_withDot.push_back(filename);
            else
                folders.push_back(filename); 
        }
        else // !isDirectory
        {
            if (startsWithDot)
                files_withDot.push_back(filename); 
            else
                files.push_back(filename);
        }
    }

commented Sep 1, 2025 by (6,150 points)
Hello! Thank you for your answer. I thought it was inefficient and it could be faster. Also I don't use variable to store those because it helps me navigate thru my code easily and I won't have to remember a bunch of variable names. Also I hate thinking about what to call variables. I know it might be longer but I like it that way.

Thanks for answering!
commented Sep 2, 2025 by Peter Minarik (101,340 points)
Ah, yeah, the good old problem of naming variables. That's one of the most difficult parts of writing well-maintainable code. Names are sometimes utterly useless (e.g., "tmp" or "a" or even "list" would not help to understand what is stored inside), sometimes straight misleading (e.g., calling something a "customerList", but in fact it's not of a type List, but it's an Array).

Naming functions and classes can also be difficult.

And there's also maintainability. You can call the collection of customers "customerArray", but if you change it to a List, instead of an actual array, then either the name becomes misleading, or you'd need to rename the variable to "customerList". Best practice is just to call them "customers" and not encode the type in the variable. This would be more pronounced with something like "int32_t intNumCustomers", then you later refactor it to "uint32_t", and now you'd have to rename it to "uintNumCustomers". Again, best practice is not to include the type in the name, just call it "numCustomers" or something similar.
–1 vote
answered Sep 9, 2025 by (210 points) 1 flag

through that piece of code? Have you done a performance analysis to find out why it is slow? What part of the code makes it slow?

You have to iterate through the files anyway; you cannot avoid that. What you could avoid is doing the same thing multiple times.

E.g. fs::is_directory(entry.path()) is called 4 times. You could just store it in a variable inside your loop once, and not evaluate this expression 4 times in your code.

Same for filename.starts_with(".").

Anything that you use multiple times could be stored in a variable.

Something like this (I haven't made sure the code compiles, though!)

    for(const auto& entry : fs::directory_iterator(path))
    {
        // Cached values as they will be used multiple times
        auto path = entry.path();
        string filename = path.filename().string();
        bool startsWithDot = filename.starts_with(".");
        bool isDirectory = fs::is_directory(path);

        if (isDirectory)
        {
            if (startsWithDot)
                folders_withDot.push_back(filename);
            else
                folders.push_back(filename); 
        }
        else // !isDirectory
        {
            if (startsWithDot)
                files_withDot.push_back(filename); 
            else
                files.push_back(filename);
        }
    }
+1 vote
answered Sep 15, 2025 by Edcel Castor (280 points)
We can consider creating a function that takes a collection as input and pushes its elements into  inorder , then call that function for each collection.
0 votes
answered Sep 29, 2025 by A1010 (330 points)

你比我強! ! ! !但是我建議問AI喔!

0 votes
answered Feb 13 by (370 points)
vector<vector<string>*> all_vectors = { &folders_withDot, &folders, &files_withDot, &files };

for (auto vec_ptr : all_vectors) {
    inorder.insert(inorder.end(), vec_ptr->begin(), vec_ptr->end());
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...