tags:

views:

191

answers:

2

I was thinking that dynamic arrays were a replacement for vectors in D, but it seems they have no remove function (only associative arrays do) which is rather a limitation for a vector so I'm wondering if I've got that right. If a have an array like follows,

uint[] a;
a.length = 3;
a[0] = 1;
a[1] = 2;
a[2] = 3;

Then the only way I've found to remove, say, the second element is,

a = a[0..1] ~ a[2];

But that doesn't seem right (but maybe only because I don't understand this all yet). So is there a vector and is there another way of removing an element from a dynamic array?

Thanks.

+2  A: 

In std.container there is an Array!T template, which appears to be much like std::vector from C++.

Array!int a = [0, 1, 2, 3];
a.linearRemove(a[1..3]);
assert(equal(a, [0, 3]));

Unfortunately it does not appear to have an individual remove method, although you could always use linearRemove with a singleton range.

Peter Alexander
+4  A: 

You could use std.algorithm.remove(), which works not only with arrays but with generic ranges. Example:

import std.algorithm;

void main() {
    uint[] a = [1, 2, 3];
    a = a.remove(1);
    assert(a == [1, 3]);
}
dsimcha
True, though Array would likely be better if what you're really looking for is a vector, since Array doesn't have to resize its internal array every time that you add or remove anything to/from it.
Jonathan M Davis
@Jonathan: Do you know if that's a requirement of the language specification, or is it implementation defined? i.e. Could a compiler implement the built-in array like `std.container.Array`?
Peter Alexander
I don't know what the exact requirements are. The compiler has some leeway, but I very much doubt that it will (and I don't think that it should) allocate double the memory that it needs in the general case. Arrays do have a capacity property that tells you how many elements you can append to it before it will have to be reallocated, and if you play around with it, you can see that it definitely keeps some extra memory there, but it would arguably be a bit of a memory hog if it tried to keep as much extra memory as Array does. http://www.digitalmars.com/d/2.0/arrays.html
Jonathan M Davis
No need to allocate double memory. For example,`std::vector` typically only allocates up to 50% more (so, 25% more on average), which isn't too extravagant. I'd much rather it allocated a bit more memory every now and then than allocating on every concatenation.
Peter Alexander