Removing elements from dynamic arrays in D

Removing elements from associative arrays in D is easy, as we can use the handy “remove” method. When it comes to regular dynamic arrays, however, the story is a little different. There is no such method for removing elements and the documentation doesn’t make it completely obvious.

To complicate the situation more, the technique required depends on the version of D you are using.
DMD version 2.060 is out and with it comes the deprecation of std.algorithm.indexOf. Instead, std.algorithm.countUntil should be used in its place.

Here is an example:

import std.stdio;
import std.algorithm;

void main(string[] args) {

	auto items= ["item1", "item2", "item3"];
	auto index = countUntil(items, "item2");
	writefln("Index of 'item2' is: %d", index);
	auto mutated = remove(items, index);


It generates the following output:

["item1", "item2", "item3"]
Index of 'item2' is: 1
["item1", "item3"]


Comments are closed.