你要做的是 C++ 中一个叫做“初始化列表”的即将到来的 现有特性,通过它可以使用= {} 来对向量或列表进行初始化。我不知道它是否已经在 TR1 中发布了,或者可能会在 TR2 中发布。
#include <vector>
#include <list>
#include <iostream>
using namespace std;
int main(void) {
vector<int> vi = {1, 2, 3, 4, 5};
list<int> li = {5, 4, 3, 2, 1, 0};
cout<<"vector size="<<vi.size()<<", list size="<<li.size()<<endl;
return 0;
}
你所使用的代码在我看来不太合适。如果你想要实现包含结构体(树)的结构,可以在节点内包含指向结构体/节点的指针列表(如果无法实现,也可以只用void指针)。
大多数菜单结构本质上都是基于有序列表的树形结构(一个地方有n个节点,但在其他地方可能有m个节点等)。Robert Sedgewick编写了一本名为《C++算法》的教材。
#include <vector>
#include <iterator>
#include <string>
void * pRoot = NULL;
class CTreenode;
class CTree;
class CTree {
public:
vector<class CTreeNode> lctnNodeList;
vector<class CTreeNode>::iterator lctni;
public:
CTree() {}
~CTree() {
for (lctni=lctnNodeList.begin(); lctni != lctnNodeList.end(); nctni++) {
if (NULL==lctni->getChildPtr()) {
} else {
delete (CTree *)lctnNodeList.pChild;
}
}
}
void addToList(string& data, CTree * p) {
CTreeNode ctn(data, p);
lctnNodeList.push_back(d);
}
void eraseAt(size_t index) {
vector<class CTreeNode>::iterator i = lctnNodeList.begin();
vector<class CTreeNode>::iterator i2 = lctnNodeList.begin();
i2++;
size_t x;
for (x=0; x <= index; x++,i++,i2++) {
if (index == x) {
lctnNodeList.erase(i,i2);
break;
}
}
}
void at(size_t index, string& returndata, CTree * &p) {
vector<class CTreeNode>::iterator i = lctnNodeList.begin();
size_t x;
for (x=0; x <= index; i++,x++) {
if (x==index) {
i->getData(returndata, p);
break;
}
}
}
const CTreeNode& operator[](const size_t idx) {
if (idx < lctnNodeList(size)) {
return lctnNodeList.at(idx);
} else {
}
}
const size() {
return lctnNodeList.size();
}
doActionToThisSubtree(void * root) {
CTree * pct = (CTree *)root;
for (pct->lctni=pct->lctnNodeList.begin(); pct->lctni != pct->lctnNodeList.end(); pct->nctni++) {
if (NULL==pct->lctni->getChildPtr()) {
} else {
doActionToThisSubtree(pct->lctni->getChildPtr());
}
}
}
};
class CTreeNode {
public:
CTree * pChild;
string sData;
public:
CTreeNode() : pChild(NULL) {}
CTreeNode(string& data, pchild) : pChild(pchild) {
sData = data;
}
~CTreeNode() {
if (NULL!=pChild) {
delete pChild;
pChild = NULL;
}
void getChild(CTreeNode& child) {
child = *pChild;
}
bool addChild(string& s) {
if (NULL==pChild) {
return false;
} else {
pChild = new CTree;
}
return true;
}
void * getChildPtr() { return pChild; }
void getData(string& data, CTree * &p) {
data=sData;
p = pChild;
}
void setData(string& data, CTree * p) {
sData=data;
pChild = p;
}
};
问题在于这里存在相互依赖,我认为通过类声明已经解决了这个问题。
在类CTree之前声明类CTreeNode;。
http://www.codeguru.com/forum/showthread.php?t=383253
我可能会弄乱这段代码,并且它是不完整的,因为我多年来没有写过树,但我认为我已经涵盖了基础知识。我没有实现operator[]。