#ifndef TREE_H #define TREE_H /////////////////////////////////////////////////////////////////////////// // Tree.h - demonstrates how to define a template m-ary tree class // // ver 1.2 // // Language: Visual C++, 2008 // // Platform: Dell Precision T7400, Vista Ultimate, SP1 // // Application: CSE687 - Demo for Project #1, Spring 2009 // // Author: Jim Fawcett, Syracuse University, CST 4-187, // // (315) 443-3948, jfawcett@twcny.rr.com // /////////////////////////////////////////////////////////////////////////// /* * Module Operations: * ================== * Provides a template Tree class that holds a finite number of nodes and * and supports visitation of each node, using depth first search. * * Build Process: * ============== * cl /D:TEST_TREE Tree.cpp Nodes.cpp * * Maintenance History: * ==================== * ver 1.2 : 29 Jan 10 * - added some comments below and in code * ver 1.1 : 27 Jan 10 * - added private declarations for copy and assignment * to prevent compiler from generating incorrect versions * ver 1.0 : 23 Jan 09 * - first release */ /* * Notes: * - Tree destructor is not deleting nodes because the test stub is creating * on the stack, e.g., local to main. If you create nodes on the heap * then you should delete all the contents pointed to by the nodes vector. * - This simple tree depends on user to assemble the linked structure, as * done in the test stub. Since you will get a fully linked tree from the * XmlParser stack in Project #1, this tree can just accept that structure. */ #include #include "Nodes.h" namespace AbstractDataTypes { template class Operation { public: virtual ~Operation() {} virtual void operator()(MNode* pNode) { std::cout << "\n " << pNode->value(); } }; template class Tree { public: Tree(Operation* pOper=new Operation()); ~Tree(); void setOperation(Operation* pOper); void add(MNode* pMNode); bool remove(MNode* pMNode); void clearMarks(); void walk(MNode* pStart); private: Tree(const Tree& tree); Tree& operator=(const Tree& tree); MNode* pRoot; // not used yet std::vector*> nodes; // used to unmark Operation* pOper_; }; template Tree::Tree(Operation* pOper) : pOper_(pOper) {} template Tree::~Tree() { delete pOper_; // Do this only if you create nodes on heap // for(size_t i=0; i void Tree::setOperation(Operation* pOper) { delete pOper_; pOper_ = pOper; } template void Tree::add(MNode* pMNode) { nodes.push_back(pMNode); } template bool Tree::remove(MNode* pMNode) { std::vector< MNode* >::iterator iter; for(iter=nodes.begin(); iter!=nodes.end(); ++iter) { if(*iter == pMNode) { nodes.erase(iter); return true; } } return false; } template void Tree::clearMarks() { for(size_t i=0; iisMarked() = false; } template void Tree::walk(MNode* pStart) { (*pOper_)(pStart); MNode* pTemp; for(size_t i=0; inextUnmarkedChild(); if(pTemp == 0) return; pTemp->isMarked() = true; walk(pTemp); } } } #endif