65.9K
CodeProject is changing. Read more.
Home

Simple STL tree

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.23/5 (40 votes)

Dec 2, 2003

viewsIcon

109252

Simple way to create tree structure using basic STL classes

Introduction

One day I was searching for a easy and simple tree implementation using STL. I didn't find anything useful and invented a very simple way to do this.

Background (optional)

Basic idea is to use a standard tree structure:

// Simple tree

class CTreeItem
{
   // Tree Item properties
   ...
   //
   vector<CTreeItem*> children;
};

We can expand simple tree definition using templates to:

// Simple tree
#include <vector>

// Template definition

template<class CItem> class CTree
{
public:
   // Tree Item properties
   CItem item;
   
   // Children items
   std::vector<CTree*> children;
};

Using the code

Using this simple template we can create tree structures and operate with them easily:

// 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);

That's it. This class can be extended to destroy all children objects during parent destruction.