STLVisual C++ 7.1Visual C++ 7.0Windows 2003Windows 2000Visual C++ 6.0Windows XP中级开发Visual StudioWindowsC++
简单的 STL 树






1.23/5 (40投票s)
2003年12月2日

109669
使用基本 STL 类创建树结构的简单方法。
引言
有一天,我正在寻找一个简单易用的基于 STL 的树实现。我没有找到任何有用的东西,于是发明了一种非常简单的方法来实现它。
背景(可选)
基本思想是使用标准的树结构。
// Simple tree class CTreeItem { // Tree Item properties ... // vector<CTreeItem*> children; };
我们可以使用模板扩展简单的树定义为
// Simple tree #include <vector> // Template definition template<class CItem> class CTree { public: // Tree Item properties CItem item; // Children items std::vector<CTree*> children; };
使用代码
使用这个简单的模板,我们可以创建树结构并轻松地对其进行操作。
// Example class Location { public: std::string name; long code; }; // Create tree items CTree<Location> Country, Washington, NewYork; Country.item.name = "USA"; Country.item.code = 1; Washington.item.name = "Washington"; Washington.item.code = 2; NewYork.item.name = "New York"; NewYork.item.code = 1; Country.children.push_back(&Washington); Country.children.push_back(&NewYork);
就这样。这个类可以扩展,以便在父对象销毁时销毁所有子对象。