我用的是GCC4.7.0,Ubuntu 12.04,CMake.
现在看看tree.h中的实现。
- #ifndef _TREE_H
- #define _TREE_H
- #include <vector>
- #include <memory>
- namespace freebird {
- template<typename T>
- class node{
- public:
- node(T value):value_(value){
- }
- /**
- * insert child node to the end
- */
- void push_back(std::shared_ptr<node<T>> child){
- children_.push_back(child);
- }
- typedef typename std::vector<shared_ptr<node<T>>>::iterator iterator_type;
- void insert(iterator_type pos,std::shared_ptr<node<T> > child){
- children_.insert(pos,child);
- }
- T value() const {
- return value_;
- }
- /**
- * iterator to the first child
- */
- iterator_type begin(){
- return children_.begin();
- }
- /**
- * Get the end iterator of children
- */
- iterator_type end(){
- return children_.end();
- }
- private:
- T value_;
- std::vector<shared_ptr<node<T>>> children_;
- };
- template<typename T>
- class tree {
- public:
- tree<T>(){
- }
- void root(T node){
- root_ = node;
- }
- T root() {
- return root_;
- }
- private:
- T root_;
- };
- }
- #endif
实现还是挺简单的,用了一个vector,里面存放了shared_ptr<node<T>>,因此删除的时候不要手动delete。只是小心不要在树里面节点形成回路,那是shared_ptr最忌讳的。‘
