Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) NewickToString

 

NewickToString is a Newick code snippets to convert a Newick to std::string.

 

struct BinaryNewickVector
{
  enum { bracket_open  = -1 };
  enum { bracket_close = -2 };
  enum { comma         = -3 };
  enum { new_line      = -4 };
  enum { null          = -5 };
};

///NewickToString converts a Newick std::vector<int> to a
///standard-format std::string.
///From http://www.richelbilderbeek.nl/CppNewickToString.htm
const std::string NewickToString(const std::vector<int>& v)
{
  assert(v.size() > 2 && "A Newick must at least have one single value");
  assert(v[0] == BinaryNewickVector::bracket_open
    && "A std::vector<int> Newick must start with a bracket_open");
  assert(v[v.size() - 1] == BinaryNewickVector::bracket_close
    && "A std::vector<int> Newick must end with a bracket_close");
  std::string s;
  s.reserve(2 * v.size()); //Just a guess
  const int sz = v.size();
  for (int i=0; i!=sz; ++i)
  {
    const int x = v[i];
    if (x >= 0)
    {
      s+=boost::lexical_cast<std::string>(x);
      assert(i+1<sz && "Must not end with number");
      const int next = v[i+1];
      if (next > 0 || next == BinaryNewickVector::bracket_open)
      {
        s+=",";
      }
    }
    else if (x==BinaryNewickVector::bracket_open)
    {
      s+="(";
    }
    else if (x==BinaryNewickVector::bracket_close)
    {
      s+=")";
      //Final closing bracket?
      if (i+1==sz) break;
      const int next = v[i+1];
      if (next > 0 || next == BinaryNewickVector::bracket_open)
      {
        s+=",";
      }
    }
    else
    {
      assert(!"Should not get here"
        && "A std::vector<int> Newick must consist of brackets and values only");
    }
  }
  return s;
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict