要求是--某个文件中存储了一个最多3层的层级结构,其中每个元素都是一个自然数,它的存储方法是一个二元组的列表,每个二元组的形式为:(元素,父元素)。现在希望能够通过读取该二元组列表,打印出目录的层级结构。

源代码部分

文件Element.h:
#include <string>
#include <vector>
class CElement
{
public:
CElement(void);
~CElement(void);
std::vector<CElement> getChild(std::vector<CElement> v); public:
int ele1;
int ele2;
int level;
CElement *child;
std::string output;
}; 文件Element.cpp:
#include "Element.h" CElement::CElement(void)
{
} CElement::~CElement(void)
{
} std::vector<CElement> CElement::getChild(std::vector<CElement> v)
{
std::vector<CElement> e;
std::vector<CElement>::iterator first = v.begin();
std::vector<CElement>::iterator last = v.end();
for(;first != last;++first)
{
if(first->ele2 == ele1)
e.push_back( *first);
}
return e;
}
文件main.cpp
#include "Element.h"
#include <iostream>
#include <vector> void setLevel(std::vector<CElement> &v)
{
std::vector<CElement>::iterator first = v.begin();
std::vector<CElement>::iterator last = v.end();
for(; first != last; ++first)
{
if(first->ele2 == 0)
{
first->level = 1;
}
else
{
std::vector<CElement>::iterator beg = v.begin();
std::vector<CElement>::iterator ed = v.end();
for(; beg != ed; ++beg)
{
if(first->ele2 == beg ->ele1)
{
if(beg->ele2 == 0)
first->level = 2;
else
first->level = 3;
} }
}
}
} int _tmain(int argc, _TCHAR* argv[])
{
int a[16][2] = {
{1,},{5,1},{6,1},{12,6},{13,6},{2,},{3,},{4,},{7,1},{8,2},{9,2},{10,3},{11,8},{14,5},{15,3},{16,15}
};
std::vector<CElement> v;
for(int i = 0;i < 16; i++)
{
CElement e;
e.ele1 = a[i][0];
e.ele2 = a[i][1];
v.push_back(e);
}
setLevel(v);
std::vector<CElement>::iterator first = v.begin();
std::vector<CElement>::iterator last = v.end();
/*
for(; first != last; ++first)
{
std::cout<< (*first).ele1<<" "<< (*first).ele2<< " "<<(*first).level<<std::endl;
}
*/
std::vector<CElement> v1;
std::vector<CElement> v2;
for(; first != last; ++first)
{
if(first->level==1)
{
std::cout<<first->ele1<<std::endl;
v1 = first->getChild(v);
for(int j =0;j<v1.size();++j)
{
std::cout<<"-"<<v1[j].ele1<<std::endl;
v2 = v1[j].getChild(v);
if(v2.size() > 0)
for(int k =0;k<v2.size();++k)
std::cout<<"--"<<v2[k].ele1<<std::endl;
}
}
}
int t;
std::cin>>t;
return 0;
}

实际跑出来的图

读取二元组列表,打印目录的层级结构-----C++算法实现-LMLPHP

05-04 08:17