Search code examples
d

Better way to save removed value from array, using std.algorithm


I need to remove the first element from an array, that is present in a second array.

Looking through the std.algorithm package, I can get part way there with findAmong and remove.

But is there a way to combine these, so that I can both remove an element, and see which element was removed?

For example:

// array that will have elements removed
auto targetStrings = ["a", "b", "c"];
// holder for element that will be removed
string removedString;
// array to match against, to determine what should be removed
auto removeStrings = ["b", "a"];

auto r = findAmong(targetStrings, removeStrings);
if (r.count > 0) {
  removedString = r[0];
  targetStrings = targetStrings.remove!(c => c == removedString);
}

writeln(removedString);
writeln(targetStrings);

Solution

  • You can get the element's index by subtracting the length of the remaining range returned by findAmong from the length of the original range, and then just use remove with the index:

    auto r = findAmong(targetStrings, removeStrings);
    if (!r.empty)
    {
        removedString = r.front;
        auto index = targetStrings.length - r.length;
        targetStrings = targetStrings.remove(index);
    }
    

    Alternatively, get the index directly with countUntil:

    auto index = targetStrings.countUntil!(s => removeStrings.canFind(s));
    if (index >= 0)
    {
        removedString = targetStrings[index];
        targetStrings = targetStrings.remove(index);
    }