Thread overview
Removing an element from a DList
Oct 17, 2023
Joakim G.
Oct 17, 2023
monkyyy
Oct 18, 2023
Christian Köstlin
October 17, 2023

For some reason I cannot remove an element from a DList. I tried several range approaches but to no avail. I'm a noob.

In the end I did this:

private void removeFromWaitingQueue(uint jid) {
    auto arr = waitingQueue[].array;
    arr = arr.remove!(job => job.jid == jid);
    waitingQueue.clear();
    foreach(job; arr) {
        waitingQueue.insertBack(job);
    }
}

Any hints?

/J

October 17, 2023

On Tuesday, 17 October 2023 at 17:27:19 UTC, Joakim G. wrote:

>

For some reason I cannot remove an element from a DList. I tried several range approaches but to no avail. I'm a noob.

In the end I did this:

private void removeFromWaitingQueue(uint jid) {
    auto arr = waitingQueue[].array;
    arr = arr.remove!(job => job.jid == jid);
    waitingQueue.clear();
    foreach(job; arr) {
        waitingQueue.insertBack(job);
    }
}

Any hints?

/J

"ranges are views of data" blah blah blah that remove function returns a fancy pointer and is lazy not the sane eager "unsafe" thing, the std avoids mutation to an unhelpful degree also std.containeers is awful

Id suggest using dynamic arrays swapping the last element to index then length--; or nullable static arrays; or just using filter if a functional approach is on the table.

October 18, 2023

On Tuesday, 17 October 2023 at 17:27:19 UTC, Joakim G. wrote:

>

For some reason I cannot remove an element from a DList. I tried several range approaches but to no avail. I'm a noob.

In the end I did this:

private void removeFromWaitingQueue(uint jid) {
    auto arr = waitingQueue[].array;
    arr = arr.remove!(job => job.jid == jid);
    waitingQueue.clear();
    foreach(job; arr) {
        waitingQueue.insertBack(job);
    }
}

Any hints?

/J

import std.container : DList;
import std.algorithm : find;
import std.range : take;
import std.stdio : writeln;
import std.range : take;
struct Job
{
    int id;
}
int main(string[] args)
{
    auto list = DList!Job(Job(1), Job(2), Job(3));
    int idToDelete = 2;
    auto toRemove = list[].find!(job => job.id == idToDelete).take(1);
    if (!toRemove.empty)
        list.linearRemove(toRemove);

    foreach (i; list[])
    {
        writeln(i);
    }

    return 0;
}

works for me ... see https://run.dlang.io/is/OtX820 for a live version.

Kind regards,
Christian