Chinaunix首页 | 论坛 | 博客
  • 博客访问: 268833
  • 博文数量: 84
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 927
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-06 23:00
个人简介

growing

文章分类

全部博文(84)

文章存档

2017年(6)

2016年(61)

2015年(17)

我的朋友

分类: C/C++

2016-05-17 09:40:27

开一个二维数组来存边的信息

  1. #pragma once

  2. template<class V,class E>
  3. class GraphMatrix
  4. {
  5. public:
  6.     GraphMatrix(size_t size,V * array)
  7.         :_vArray(new V[size])
  8.         ,_size(size)
  9.     {
  10.         for(int i = 0;i < size;++i)
  11.         {
  12.             _vArray[i] = array[i];
  13.         }

  14.         _edges = new E*[size];
  15.         for(int i = 0; i < size;++i)
  16.         {
  17.             _edges[i] = new E[size];
  18.             memset(_edges[i],E(),sizeof(E)*size);
  19.         }
  20.     }
  21.     ~GraphMatrix()
  22.     {
  23.         delete[] _vArray;
  24.         _vArray = NULL;
  25.         for(int i = 0;i < _size;++i)
  26.         {
  27.             delete[] _edges[i];
  28.         }
  29.         delete[] _edges;
  30.         _edges = NULL;

  31.         _size = 0;
  32.     }
  33. public:
  34.     size_t GetIndex(const V& v)
  35.     {
  36.         for(int i = 0;i < _size;++i)
  37.         {
  38.             if(_vArray[i] == v)
  39.             {
  40.                 return i;
  41.             }
  42.         }
  43.         return -1;
  44.     }
  45.     void AddEdges(const V&src,const V&dst,const E&w)
  46.     {
  47.         size_t SrcIndex = GetIndex(src);
  48.         size_t DstIndex = GetIndex(dst);

  49.         if(SrcIndex != -1 && DstIndex != -1)
  50.         {
  51.             _edges[SrcIndex][DstIndex] = w;
  52.             _edges[DstIndex][SrcIndex] = w;
  53.         }
  54.     }
  55.     void Display()
  56.     {
  57.         for (int i = 0; i < _size; ++i)
  58.         {
  59.             cout << _vArray[i] << " ";
  60.         }
  61.         cout << endl;

  62.         for (int i = 0; i < _size; ++i)
  63.         {
  64.             for (int j = 0; j < _size; ++j)
  65.             {
  66.                 cout << _edges[i][j] << " ";
  67.             }
  68.             cout << endl;
  69.         }
  70.         cout << endl;
  71.     }
  72. protected:
  73.     V* _vArray;
  74.     E **_edges;
  75.     size_t _size;
  76. };


阅读(1255) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~