5.3 C++-style Iteration

C++ iteration is designed to more closely mimic iterator loops as written in C++ OEChem (to aid in porting) but it also provides a much more rich interface, including things like the ability to iterate backwards as well as forwards.

Methods that support this style include:

Method Java C++
Creation OEAtomBaseIter i; OEIter<OEAtomBase> i;
Increment i.Increment() $++$i;
Decrement i.Decrement() $--$i;
Increment by n i.Increment(n) i += n;
Decrement by n i.Decrement(n) i -= n;
Go to first i.ToFirst(); i.ToFirst()
Go to last i.ToLast(); i.ToLast()
De-reference (access the object) i.Target() operator ->
pointed to, i.e. OEAtomBase)    
Validity i.IsValid() operator bool

To loop forward over the atoms of a molecule:

for (OEAtomBaseIter aiter=mol.GetAtoms();aiter.IsValid();aiter.Increment()) {
  OEAtomBase atom = aiter.Target();
  System.out.println(atom.GetAtomicNum());
}

or without the temporary OEAtomBase object:

for (OEAtomBaseIter aiter=mol.GetAtoms();aiter.IsValid();aiter.Increment()) {
  System.out.println(aiter.Target().GetAtomicNum());
}

Iterating backwards over the atoms is just as easy. This next listing also shows how iterators can be re-used.

OEAtomBaseIter aiter = mol.GetAtoms();

// C++ style for loop, backwards over atoms
for (aiter.ToLast();aiter.IsValid();aiter.Decrement()) {
  System.out.println(aiter.Target().GetAtomicNum());
}

// move iterator back to end and loop backward with C++ style while loop
aiter.ToLast();
while(aiter.IsValid()) {
  System.out.println(aiter.Target().GetAtomicNum());
  aiter.Decrement();
}