#include <string> #include <vector> #include <map> #include <list> #include <algorithm> using namespace std; const char *pLevArr[] = { "1", "2", "211", "211113", "2211", "3", "4", "412", "413", "421111111", "5" }; const int LV_SIZE = sizeof(pLevArr)/sizeof(void*); void create_lev(const char** plv, int len, vector<string> &vecLev) { copy(plv, plv + len, insert_iterator<vector<string> >(vecLev, vecLev.begin())); } class Unit { public: typedef vector<Unit*>::iterator iterator; Unit(const string& name):_name(name), _parent(NULL){} void setParent(Unit* parent){_parent = parent;} void setChild(vector<Unit*> &childs){_childs = childs;} iterator begin(){ return _childs.begin();} iterator end() {return _childs.end();} size_t size(){ return _childs.size();} Unit* getParent(){return _parent;} private: Unit *_parent; vector<Unit*> _childs; string _name; }; class AttchParent { public: AttchParent(Unit *parent):_parent(parent){} void operator () (Unit *pUnit) { pUnit->setParent(_parent); } private: Unit *_parent; }; // every time create one level Unit Unit *create_unit_imp(vector<string>::iterator &curIt, vector<string>::iterator endIT , size_t lev , const string& levChar) { vector<Unit*> thisLevUnits; string levStr((*curIt).begin(), (*curIt).begin() + lev); while (curIt < endIT) { if ((*curIt).empty()) { ++curIt; continue; } // check current unit's layer if (lev == 0 // root layer || ((*curIt).size()>lev && equal(levChar.begin(), levChar.end(), (*curIt).begin()))) { // step into next layer ++lev; // belong to this level if ((*curIt).size() == lev) { Unit* pUnit = new Unit(*curIt); thisLevUnits.push_back(pUnit); ++curIt; } // belong to deeper layers else { thisLevUnits.push_back(create_unit_imp(curIt, endIT, lev, string((*curIt).begin(), (*curIt).begin()+lev))); } // setp out this layer --lev; } // It does not belong to this layer else { break; } } // create unit for this level Unit *pThisLevelUnit = new Unit(levStr); // set units relationship pThisLevelUnit->setChild(thisLevUnits); for_each(thisLevUnits.begin(), thisLevUnits.end(), AttchParent(pThisLevelUnit)); return pThisLevelUnit; } Unit *create_unit(vector<string> levles) { return create_unit_imp(levles.begin(), levles.end(), 0, ""); } // Depth First void adjust_unit(Unit *pUnit) { if (pUnit->size() == 0) { return; } Unit::iterator it = pUnit->begin(); for (; it != pUnit->end(); ++it) { adjust_unit(*it); // root node, but has only one child if ((*it)->size() == 1) { // use child unit to replace it Unit* pDel = *it; *it = *((*it)->begin()); delete pDel; } } } int main() { vector<string> vecLevStr; create_lev(pLevArr, LV_SIZE, vecLevStr); Unit *pUnit = create_unit(vecLevStr); adjust_unit(pUnit); };