On Sunday, 1 October 2023 at 11:43:17 UTC, bachmeier wrote:
On Sunday, 1 October 2023 at 11:39:11 UTC, bachmeier wrote:
On Sunday, 1 October 2023 at 09:01:53 UTC, dhs wrote:
Hi,
Is there a straight forward Array type in D similar to C++'s
vector class? Something along the lines of the tuple:
(pointer to elements, length, capacity).
I tried two implementations: D's dynamic array and
std.container.array.
When D creates a dynamic array, it returns a slice. Functions
that add or remove elements begin by asking the memory
manager for the dynamic array that the slice belongs to. Only
then can they go on and add elements.
Have you read [this
article](https://dlang.org/articles/d-array-article.html)? I'm
not sure what you mean with your reference to the memory
manager, but consider this program:
```
import std;
void main() {
int[] x;
x.length = 100;
foreach(ii; 0..100) {
x.ptr[ii] = ii;
}
x.length = 100;
writeln(x);
}
```
Or if you want a safer version:
```
import std;
void main() {
int[] x;
x.length = 100;
foreach(ii; 0..150) {
if (ii < x.length) {
x.ptr[ii] = ii;
}
}
writeln(x);
}
```
Thanks for the article.
When you write x.length = 100, the code looks at x.capacity to
see if the allocated memory is big enough for 100 elements. Since
'capacity' is not part of x, the code calculates it by asking the
Garbage Collected how much memory was allocated. This is my
understanding of the code and what I meant by "asking the memory
manager".
std.container.array uses a 'capacity' field, but is reference
counted. This is not documented and means an additional
indirection, which in my case is unnecessary.
User 'Imperatorn' suggested using core.stdcpp.vector.
Unfortunately, it compile for me (neither using DMD nor LDC). In
addition, it looks like it depends on the C++ runtime for 'new'
and 'delete'.
So I am still in search of a straightforward dynamic array
similar to C++ 'vector'.