Int within ranges

nrgyzer nrgyzer at gmail.com
Mon Jun 13 11:52:24 PDT 2011


> On Mon, 13 Jun 2011 12:15:40 -0400, nrgyzer <nrgyzer at gmail.com>
wrote:
> > Hi there,
> >
> > is there any possibility to get a sliced array from another array
> > between two ranges like:
> >
> > int[uint] myArray;
> > myArray[10] = 1000;
> > myArray[20] = 2000;
> > myArray[30] = 3000;
> > myArray[40] = 4000;
> > myArray[50] = 5000;
> >
> > int[] newArray = myArray[>= 20 .. <= 40]; // not able to do this
> > writeln(newArray); // should print [2000, 3000, 4000]
> >
> > Is there any way to do this?
> import dcollections.TreeMap;
> auto myArray = new TreeMap!(uint, int);
> myArray[10] = 1000;
> myArray[20] = 2000;
> myArray[30] = 3000;
> myArray[40] = 4000;
> myArray[50] = 5000;
> // this is a little kludgy, but necessary since you require <= 40
> auto c = myArray.elemAt(40);
> c.popFront();
> int newArray = array(myArray[20..c]);
> Note two things:
> 1. int[uint] is a hash, and so has no particular order.  Therefore,
there
> is no guarantee of iteration order, or that a range of such a
container
> (if one existed) would be properly constructed with two keys.  A
TreeMap,
> or RedBlackTree, is sorted, and so the order is guaranteed.
> 2. dcollections.TreeMap is implemented with the same collection as
> std.container.RedBlackTree, so you could potentially do the same
thing
> with it.  But the dcollections.TreeMap API is more polished.
> -Steve

Exactly what I'm looking for, but how can I realize that it also
gives me the elements when the key doesn't exists like:

import std.range;
import dcollections.TreeMap;

auto myArray = new TreeMap!(uint, int);

myArray[10] = 1000;
myArray[20] = 2000;
myArray[30] = 3000;
myArray[45] = 4500;
myArray[50] = 5000;

auto c = myArray.elemAt(40);
c.popFront();
int[] newArray = array(myArray[20..c]);
writeln(newArray);

This will throw an exception because element 40 doesn't exist. Is
there any possibility to get the element 20 and 30 from this map?


More information about the Digitalmars-d-learn mailing list