proper range usage
    Ali Çehreli via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Nov  3 14:36:20 PST 2015
    
    
  
On 11/03/2015 01:12 AM, Alex wrote:
 >> That problem is solved by the convention that 'end' is one beyond the
 >> last valid element. So, when there is only the element 42, then
 >> begin==42 and end==43. Only when the last element (42 in this case) is
 >> consumed, begin==end.
 >>
 > This part is dangerous, and I'm not sure how dangerous it is.
If I understand correctly, you are referring to 'end' being one beyond. 
It is not dangerous because nobody dereferences that index. The slice is 
simply empty when beg==end.
This is how C++'s iterators work and how D's number ranges work:
     foreach (i; 0 .. 3) {
         arr[i];    // i will not be 3
     }
 > Now, I
 > have to dive into my structure a little bit deeper:
 > Say, I have three classes:
 >
 >
 > class B //current structure
 > {
 >      M[] _ms;
 >      P[] _ps;
 >      P[M] assoc;
 > }
 >
 > struct M
 > {
 >      int id;
 >      alias id this;
 > }
 >
 > struct P
 > {
 >      int id;
 >      alias id this;
 >      int begin;
 >      int end;
 > }
 > The idea is, that P structs are disjunct (and contigous, if this does
 > matter) arrays of M's. And the question is, what happens, if I set the
 > end property of a P to a number, which belongs to another P.
That's fine. D's slices do that all the time: arr[0..3] and arr[3..$] 
seem to share index 3 but it is not the case: The first slice does not 
use it but the second one does.
Aside: If 'begin' and 'end' are indexes into an actual array (of Ms? I 
forgot), perhaps you can keep slices instead:
struct P
{
      int id;
      alias id this;
      M[] ms;    // <--
}
It would be almost as efficient but larger: Altough you use two ints 
(total 8 bytes), a slice is 16 bytes on a 64-bit system: a pointer and a 
size_t.
Ali
    
    
More information about the Digitalmars-d-learn
mailing list