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

  • 相关阅读:
    Java面向对象XMind
    使用idea插件JRebel热部署的坑
    Mysql小技巧(多行数据合并+模糊查询
    JRebel安装使用
    Shiro(三) 权限管理 假数据
    Shiro(二)通过shiro实现登录 连接数据库+集成Springboot
    Shiro(一)通过shiro实现登录
    poi实现Excel输出
    日志,注解切入点
    获取用户信息
  • 原文地址:https://www.cnblogs.com/yzm10/p/7228831.html
Copyright © 2011-2022 走看看