5.5 Looping over the Neighbors of an Atom

Often it is not the bonds around the atom that you wish to loop over but the neighboring atoms. One way to do this would be to use a OEBondBase iterator, and then use the OEBondBase method GetNbr which takes an OEAtomBase* as input, and returns the OEAtomBase* of the atom across the bond from the input atom.

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

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

void ShowNeighbors(OEAtomBase *atm)
{
  OEIter<OEBondBase> bond;
  OEAtomBase *nbor;

  cerr << "Neighbors: ";
  for (bond = atm->GetBonds(); bond; ++bond)
  {
    nbor = bond->GetNbr(atm);
    cerr << nbor->GetIdx() << " ";
  }
  cerr << endl;
}

int main()
{
  OEMol mol;
  OEParseSmiles(mol, "c1ccccc1");

  OEIter<OEAtomBase> atom;
  for (atom=mol.GetAtoms();atom;++atom)
  {
    cerr << "Atom: " << atom->GetIdx() << " ";
    ShowNeighbors(atom);
  }
  return 0;
}

However, this can be done even more conveniently using the OEAtomBase GetAtoms method, which returns the iterator of neighboring atoms to an atom.

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

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

void ShowNeighbors(OEAtomBase *atm)
{
  OEIter<OEAtomBase> nbor;

  cerr << "Neighbors: ";
  for (nbor = atm->GetAtoms(); nbor; ++nbor)
  {
    cerr << nbor->GetIdx() << " ";
  }
  cerr << endl;
}

int main()
{
  OEMol mol;
  OEParseSmiles(mol, "c1ccccc1");

  OEIter<OEAtomBase> atom;
  for (atom=mol.GetAtoms();atom;++atom)
  {
    cerr << "Atom: " << atom->GetIdx() << " ";
    ShowNeighbors(atom);
  }
  return 0;
}