www.digitalmars.com         C & C++   DMDScript  

D - arrays as containers

One of the things I like about C++ is the basic container concept, where 
algorithms can be applied to any set of iterators.  It's pretty easy to 
replicate in D for new types, but dynamic arrays as native types 
complicate things a tad.  First, they don't have "begin" and "end" 
properties.  We could change the semantics like so:

iterator i = begin( myarray );

though I havn't decided if I like it yet.  Iterator semantics can be 
preserved, however, because pointers still work like pointers:

int[2] x;
x[0] = 1;
x[1] = 2;
int* end = &x[x.length-1];
for( int* i = &x[0]; i != end; ++i )
     printf( "%i\n", *i );

That leaves associative arrays, which looks to be a bit more 
complicated, but I think could follow similar principles--the keys and 
values arrays would likely be stored in the iterator, along with an 
index id.

There are still some differences though.  If an iterator has already 
been created, operations on the map won't be reflected in the iterated 
sequence unless the keys and values arrays are requeried.  And I guess a 
side-issue is efficiency.  Are associative arrays hashed containers, 
balanced trees?

I'm starting to think it makes sense to use external functions for just 
about everything, as it fits best with the default types.  And 
module-level access restrictions seem to support this idea.  But are C++ 
style containers the best way to go?  I haven't seen anything better, 
but then I haven't looked very hard.  My principal concern is that it be 
possible to create algorithms that can operate on a sequence returned by 
any container type, and that the semantics be consistent enough that 
they work well with template operations.

Feb 11 2004