Is there such concept of a list in D?

areYouSureAboutThat areYouSureAboutThat at gmail.com
Tue Dec 13 22:51:13 UTC 2022


On Saturday, 10 December 2022 at 06:11:18 UTC, thebluepandabear 
wrote:
>
> I was wondering more if there is an object oriented way of 
> creating arrays, like in Java there is an `ArrayList`, in C++ 
> there is `std::vector`, etc.

of course there is - I mean just imagine if there wasn't ;-)

e.g (an note, it's called unsafeVector for a reason ;-)

// ----
module test;
import std;

void main()
{
     unsafeVector v = new unsafeVector(5);

     writefln("size of v is: %s", v.size());
     writeln;

     writeln("v contains:");
     for (int i = 0; i < v.size(); i++)
     {
         v[i] = i+1;
         writefln("v %s : %s", i , v[i]);
     }
     writeln;

     writeln(v[0..3]);
     writeln(v[0..$]);
     writeln(v[$-1]);
}

unittest
{
     unsafeVector v = new unsafeVector(5);

     assert(v.size() == 5);

     // NOTE: be sure to use the interface here
     // as D lets you shoot yourself in the foot
     // by giving you direct access to sz !!!
     for (int i = 0; i < v.size(); i++)
     {
         v[i] = i+1;
     }

     assert(v[0..3] == [1,2,3] );
     assert(v[0..$] == [1,2,3,4,5]);
     assert(v[$-1] == 5);

     v[2] = 999;
     assert(v[2] == 999);
}

class unsafeVector
{
   private:
     size_t *elem;
     immutable size_t sz;

   public:
     this(size_t s)
     {
         assert( isIntegral!(typeof(s)) );
         elem = cast(size_t*)new size_t[s];
         sz = s;
     }

     auto ref opIndex(size_t i)
     {
         return elem[i];
     }

     auto ref opSlice(size_t start, size_t end)
     {
         return elem[start .. end];
     }

     auto ref opDollar()
     {
         return sz;
     }

     auto size()
     {
         return sz;
     }
}
// ------------


More information about the Digitalmars-d-learn mailing list