Wednesday, May 27, 2009

Iterators::end

The greatest benefit of moving vectors and maps into the base language is an improvement in the syntax for iterators.

For example, C++:

std::vector<MyCoolType*> myVec;
myVec.push_back(new MyCoolType);
for(std::vector<MyCoolType*>::const_iterator i = myVec.begin(); i != myVec.end(); ++i)
(**i).print();


Versus D:

MyCoolType[] myVec;
myVec ~= new MyCoolType
foreach(i; myVec)
i.print();


First, the differences:
  1. Every class reference is automatically a pointer (MyCoolType[], not MyCoolType*[])
  2. Binary operator~ is used for vector concatenation (an object is promoted to a vector of size 1)
  3. Pointers to structures can use '.' It's obvious that the pointer needs to be dereferenced.
  4. "foreach" allows automatic const iteration. There is "foreach(ref i; myVec)" for non-const.
The advantages should be clear. Iteration in C++ is an abomination. Typedef's can clean things up some, but they also obscure what is really happening (error messages will likely come back as the underlying types).

I have become inoculated to these problems, partly because the Visual C++ IDE makes it easier (with auto complete). D makes it possible to be productive in Vi again... (not every machine has VStudio)

No comments: