Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectors and dynamic arrays in D

Tags:

arrays

vector

d

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.

like image 430
tjm Avatar asked Oct 10 '10 17:10

tjm


People also ask

What is the difference between vector and dynamic array?

Differences between a Vector and an ArrayA vector is a dynamic array, whose size can be increased, whereas THE array size can not be changed. Reserve space can be given for vector, whereas for arrays you cannot give reserved space. A vector is a class whereas an array is a datatype.

What are vectors and arrays?

We can think of a vector as a list that has one dimension. It is a row of data. An array is a list that is arranged in multiple dimensions. A two-dimensional array is a vector of vectors that are all of the same length.

Why are dynamic arrays called vectors?

Since you can represent a vector using an arra of elements, with time, the two concepts were equated. So, in many places, they simply are the same thing and in some languages arrays are called vectors.

What is dynamic array with example?

A dynamic array is a random access, variable-size list data structure that allows elements to be added or removed. It is supplied with standard libraries in many modern programming languages. Dynamic arrays overcome a limit of static arrays, which have a fixed capacity that needs to be specified at allocation.


1 Answers

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]);
}
like image 173
dsimcha Avatar answered Sep 21 '22 11:09

dsimcha