phobos std.container example

Ali Çehreli acehreli at yahoo.com
Fri Dec 31 00:18:34 PST 2010


novice2 wrote:

 > Woud anybody please show phobos std.container usage sample?
 > I need list/array of objects/structures.

SList is a singly-linked list, and Array is an array.

 > Every item have list/array of another objects/structures.
 > I need possibility:
 > 1) to construct such lists/arrays;

Trivial. :)

 > 2) to enumerate items

You mean iterate over the elements?

 > 3) to search item by "name" field

You can only linear search on an SList. You can do better with Array if 
it's ok to sort the elements before-hand; then you can binary search.

 > 4) insert/remove/replace item

Trivial.

 > I tried to read docs with dmd2 distribution, but failed to understand.

You're not alone. :)

An SList example:

import std.stdio;
import std.container;
import std.algorithm;

void main()
{
     SList!int myList;

     foreach (i; 0 .. 10) {
         if (i % 2) {
             /* Insert at the front */
             myList.insert(i);

         } else {
             /* Insert at the end */
             myList.insertAfter(myList[], i);
         }
     }

     /* Remove the element at the front */
     myList.removeFront();

     /* Iterate over all of the elements */
     foreach (element; myList) {
         writeln(element);
     }
}

Using it with user types is as simple as using your type instead of int:

import std.stdio;
import std.container;
import std.algorithm;
import std.string;

struct Point
{
     double x;
     double y;

     string toString()
     {
         return format("(%s,%s)", x, y);
     }
}

void main()
{
     SList!Point myList;

     foreach (i; 0 .. 10) {
         if (i % 2) {
             /* Insert at the front */
             myList.insert(Point(i, i));

         } else {
             /* Insert at the end */
             myList.insertAfter(myList[], Point(i, i));
         }
     }

     /* Remove the element at the front */
     myList.removeFront();

     /* Iterate over all of the elements */
     foreach (element; myList) {
         writeln(element);
     }
}

Other containers would be used similarly.

Ali


More information about the Digitalmars-d-learn mailing list