How can convert the folowing to D.

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 31 18:09:32 PDT 2016


On 03/31/2016 05:34 PM, learner wrote:
> Hi,
>
> I have the following code in C++.
>
> rectangles.erase(rectangles.begin() + index);
>
> where rectangles is:
> std::vector<Rectangle> rectangles;
>
> how can I do something similar in D.
>
> Learner.
>

import std.stdio;

void main() {
     int[] a = [ 1, 2, 3, 4, 5 ];
     writefln("Before: %s", a);
     size_t index = 2;
     a = a[index .. $];       // <-- HERE
     writefln("After : %s", a);
}

Note that it's a cheap operation; the elements are still in memory and 
not destroyed. If you want to run their destructors you can call 
destroy() explicitly:

import std.stdio;
import std.algorithm;
import std.range;

struct Rect {
     int i;

     ~this() {
         writefln("Destroying %s", i);
     }
}

void main() {
     Rect[] a = iota(5).map!(i => Rect(i)).array;

     writefln("Before: %s", a);

     size_t index = 2;

     // If you need to run the destructors now:
     a[0 .. index].each!((ref e) => e.destroy);

     a = a[index .. $];

     writefln("After : %s", a);
}

Prints

Destroying 0
Destroying 1
Destroying 2
Destroying 3
Destroying 4
Before: [Rect(0), Rect(1), Rect(2), Rect(3), Rect(4)]
Destroying 0
Destroying 1
After : [Rect(2), Rect(3), Rect(4)]

Ali



More information about the Digitalmars-d-learn mailing list