树数据结构的实现-节点

时间:2019-04-11 22:13:55

标签: c++ c++11 tree

我可以请您检查我的代码并给我一些提示吗,我可以在实现上做得更好吗?我希望你能判断我的五分法则。 我试图坚持好的C ++编码标准。

我有几个问题:

1。我对从vector释放数据感到困惑。我应该调用clear()还是将其与空向量交换,就像我在下面的代码中所做的那样。

  1. std::move()的工作方式。调用std::move(node)之后,我仍然必须删除所有节点元素或为我移动吗?

节点的头文件

template <typename V>
class Node
{
private:
    bool visited;
    V value;
    std::vector<Node*> children;
    V time;

public:
    Node(V value,V time);
    Node(const Node<V> &node1);
    Node( Node<V> && node1);
    Node();
    ~Node();
    /////////////////////
    Node& operator=(const Node &n1);
    Node& operator=(Node&& other);
     // more code....
};

节点的Cpp文件

template <typename V>
Node<V>::Node()
        : visited(false) , time(0) , value(0)
{
    children.clear();
}

template <typename V>
Node<V>::Node(V value,V time)
        : value(value) , time(time) , visited(false)
{
    children.clear();
}

template <typename V>
Node<V>::~Node()
{
    children.clear();
    std::vector<Node<V>*>Vec_temp;
    children.swap(Vec_temp);
    value = 0;
    time = 0;
    visited = false;
}

template <typename V>
Node<V>::Node(const Node<V>&node)
{
    value = node.get_value();
    children = node.children;
    time = node.get_time();
    visited = node.was_visited();
}

template <typename V>
Node<V>::Node(Node<V> &&node)
    : value(std::move(node.value)) , time(std::move(node.time)) , visited(std::move(node.visited)) , children(std::move(node.children))
{
    std::vector<Node<V>*>temporary;
    node.children = temporary;
    node.visited = false;
    node.value = 0;
    node.time = 0;
}

template <typename V>
Node<V>& Node<V>::operator=(const Node<V> &n1){
    if(this !=&n1) {
        std::cout << "operator = \n";
        value = n1.value;
        time = n1.time;
        visited = n1.visited;
        /// allocate new memory and coppy
        std::vector<Node<V> *> new_children;
        std::copy(n1.children.begin(), n1.children.end(), 
        std::back_inserter(new_children));
        /// deallocate old memory
        std::vector<Node<V> *> delocate;
        children.swap(delocate);
        /////
        children = new_children;
    }
    return *this;
}

template <typename V>
Node<V>& Node<V>::operator=(Node&& node){
    if( this == &node) return *this;
    /// dealacation
    children.clear();
    /// allocation
    value = node.value;
    time = node.time;
    visited = node.visited;
    children = node.children;
    /// deallocation of node
    std::vector<Node<V>*> temporary;
    node.children = temporary;
    node.visited = false;
    node.value = 0;
    node.time = 0;
return *this;
}

0 个答案:

没有答案