6.2 Looping over the Atoms and Bonds of a Molecule

The example below shows the minimal use of OEChem's iterators. These examples use the OEMolBase methods GetAtoms and GetBonds , which return iterators over the atoms and bonds of a molecule, respectively.

 1 #include "openeye.h"
 2 #include "oechem.h"
 3 #include <iostream>
 4
 5 using namespace OESystem;
 6 using namespace OEChem;
 7 using namespace std;
 8
 9 bool MyMolIsEmpty(OEMolBase &mol)
10 {
11   return mol.GetAtoms()? false : true;
12 }
13
14 unsigned int MyNumAtoms(OEMolBase &mol)
15 {
16   OEIter<OEAtomBase> atom;
17   unsigned int result = 0;
18
19   for (atom = mol.GetAtoms(); atom; ++atom)
20    ++result;
21   return result;
22 }
23
24 unsigned int MyNumBonds(OEMolBase &mol)
25 {
26   OEIter<OEBondBase> bond;
27   unsigned int result = 0;
28
29   for (bond = mol.GetBonds(); bond; ++bond)
30     ++result;
31   return result;
32 }
33
34 int main()
35 {
36   OEMol mol;
37   OEParseSmiles(mol, "c1ccccc1");
38   if (!MyMolIsEmpty(mol))
39   {
40     cerr << "num atoms: " << MyNumAtoms(mol) << endl;
41     cerr << "num bonds: " << MyNumBonds(mol) << endl;
42   }
43   return 0;
44 }

Listing:6.1 Using iterators to loop over atoms and bonds

The user function MyMolIsEmpty returns true if the input molecule has no atoms, and the functions MyNumAtoms and MyNumBonds count the number of atoms and bonds in a molecule using OEChem's iterators. These ``My*'' functions are just for demonstration, since it is far more efficient to use the OEMolBase 's NumAtoms and NumBonds methods in production code.

One point to notice is that once again C++'s destructors mean that it is not necessary to explicitly deallocate or destroy the iterator after use. Once the variable goes out of scope, it is cleaned up automatically.