Search code examples
c++readability

Which implementation is better for code readability?


I have this code, which intention is just to initialize all zones to false:

Zone per_zone;
std::fill_n(per_zone.begin(), per_zone.capacity(), false);
System per_system;
std::fill_n(per_system.begin(), per_system.capacity(), per_zone);
std::fill_n(m_pMemory->TrackingZonesShowingLogicalParcels.begin(), m_pMemory->TrackingZonesShowingLogicalParcels.capacity(), per_system);

I refactored it with the following code, because I think it express more clearly the intention, and it's shorter.

for (auto& group : m_pMemory->TrackingZonesShowingLogicalParcels)
    for (auto& system : group)
        for (auto& zone : system)
            zone = false;

I really would use algorithms because I know that - in general - algorithms express intentions more clearly than for loops, but I don't think this is the case.

Am I wrong? There is another approach that I could use to make the code more readable using the std algorithms?

Note that I don't care about performance for this. Thank you.


Solution

  • I don't know if OP can make use of C++20 or not, but the general idea of being able to iterate over a deeply nested hierarchy like this is precisely what std::ranges::join_view is for.

    Using it, you can separate the aggregation of the the target elements and the operation on the aggregated references as two distinct operations:

    #include <ranges>
    #include <vector>
    #include <algorithm>
    
    struct Memory {
        using System = std::vector<int>;
        using Group = std::vector<System>;
        std::vector<Group> TrackingZonesShowingLogicalParcels;
    };
    
     void foo(Memory* m_pMemory)
     {
         // Create a view representing all of the zones
         auto all_zones = m_pMemory->TrackingZonesShowingLogicalParcels | std::views::join | std::views::join;
    
         // use that view as if it was a container.
         std::fill(all_zones.begin(), all_zones.end(), 1);
     }