zoukankan      html  css  js  c++  java
  • STL树

    前几天觉得STL中没有树和图真是一种莫大的遗憾啊,但是在网上搜了搜,发现其实可以用容器很简单的构造树。

    还是废话少说上代码:

    struct TreeNode
    {
    DataType data; // DataType define int
    vector<TreeNode> children;
    }

    就这么简单就可以构造树的节点。

    然后我们可以简单的造一颗树

    那么我们可以写个CreateTree来创建

    复制代码
    void CreateTree(vector<TreeNode>::iterator root)
    {
    if (root->data < 1) return;
    TreeNode *NewNode;
    for (int i=1;i<=3;i++)
    {
    NewNode = new(TreeNode);
    NewNode->data = root->data - 1;
    root->children.push_back(*NewNode);
    delete NewNode;
    }
    for (vector<TreeNode>::iterator it=root->children.begin(); it!=root->children.end(); it++)
    CreateTree(it);
    }
    复制代码

    当然构造了树在内存中又看不到,所以还得写个dfs输出。

    复制代码
    void dfs(vector<TreeNode>::iterator root)
    {
    std::cout<<" "<<root->data;
    if (root->children.empty()) return;
    for (vector<TreeNode>::iterator it=root->children.begin(); it!=root->children.end(); it++)
    dfs(it);
    }
    复制代码

    有了树后添加节点神马的就很简单啦

    复制代码
    void AddNewNode(vector<TreeNode>::iterator root, DataType d)
    {
    TreeNode *NewNode;
    NewNode = new(TreeNode);
    NewNode->data = d;
    root->children.push_back(*NewNode);
    delete(NewNode);
    }
    复制代码

    可能有点同学会好奇为神马new了个新的空间后还要delete掉,这是因为所有的STL函数都是实参传形参会将new的空间拷贝一份。为了既然拷贝了那我原来new的那一份空间就没用了,就delete掉了呗。

    同样有了树后弄个动态的的图神马的也不是难事。

    比如:

    vector< vector<DataType> > g0;

    当然大家可以类推,像神马

    vector< list<int> > g1;
    list< list<int> > g2;

    然后发现link有个很有用的方法list.unique();可以将同样的元素去掉,大家用的时候注意啊,某些特定的时候会很方便的。当然有各种set也是集合性质的,但set的貌似是高度的二插平衡树。要用到线性的时候还得用list。

    以上就是这两天来的学习记录………………

    睡觉去了

    该文转自http://www.cnblogs.com/gy725/archive/2011/09/28/2194808.html

  • 相关阅读:
    听说高手都用记事本写C语言代码?真的假的!
    面向监狱编程,就靠它了!日子是越来越有判头了!
    如何把安静的程序员逼成话唠!
    想要自学编程?一个B站远远不够!
    2021年,学习C++还香吗?(文末赠书)!
    JVM--分代收集理论和垃圾收集算法
    Redis面试题
    基于RT1052 Aworks 使能GPIO输入功能(六)
    基于RT1052 Aworks 使能GPIO输出功能(五)
    基于RT1052 Aworks 使能ADC功能(四)
  • 原文地址:https://www.cnblogs.com/yzm10/p/7228831.html
Copyright © 2011-2022 走看看