5.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.

#include "oechem.h"
#include <iostream>

using namespace OESystem;
using namespace OEChem;
using namespace std;

bool MyMolIsEmpty(OEMolBase &mol)
{
  return mol.GetAtoms()? false : true;
}

unsigned int MyNumAtoms(OEMolBase &mol)
{
  OEIter<OEAtomBase> atom;
  unsigned int result = 0;

  for (atom = mol.GetAtoms(); atom; ++atom)
   ++result;
  return result;
}

unsigned int MyNumBonds(OEMolBase &mol)
{
  OEIter<OEBondBase> bond;
  unsigned int result = 0;

  for (bond = mol.GetBonds(); bond; ++bond)
    ++result;
  return result;
}

int main()
{
  OEMol mol;
  OEParseSmiles(mol, "c1ccccc1");
  if (!MyMolIsEmpty(mol))
  {
    cerr << "num atoms: " << MyNumAtoms(mol) << endl;
    cerr << "num bonds: " << MyNumBonds(mol) << endl;
  }
  return 0;
}

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, 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.