Search code examples
sortingrangehashtabled

Accessing a Hash table as a Value-Sorted Range in D


If I have a hash-table File[string] _subs and want to access its values in a sorted way is there a better way than simply through

auto ssubs = new File[_subs.length]; // preallocate sorted subs
size_t ix = 0;
foreach (sub; _subs) {
    ssubs[ix++] = sub;  // set new reference to sub
}

ssubs.sort!((a, b) => (a.timeLastModified >
                       b.timeLastModified));
return ssubs;

Solution

  • I would suggest to skip the foreach-loop and use .values, like so:

    auto ssubs = _subs.values.sort!((a, b) => (a.timeLastModified > b.timeLastModified));
    

    I think it's better to not add dependencies between elements (like with a for-loop), when they don't need it. The reason for this is that it's easier to make the code parallel without it.