Straight Forward Arrays
bachmeier
no at spam.net
Sun Oct 1 11:43:17 UTC 2023
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);
}
```
More information about the Digitalmars-d-learn
mailing list