图表

时间:2017-03-14 07:28:47

标签: c++ stl

#include <iostream>
#include<map>
#include<vector>
using namespace std;
static int index = 0;
template <typename T>
class graph
{
    private:

            typename  map< T, int > :: iterator iter;
            map <T,int> vtxMap;
            int numVertices;
            int numedges;

    public:
            void addEdge(graph<T>&, const T& ,const T&);
            void show(graph<T>&);


};

int main()
{
    graph <char> g;

    g.addEdge(g,'A','B');     // add edge AB
    g.addEdge(g,'A','C');
    g.addEdge(g,'B','D');
    g.addEdge(g,'C','D');
    g.addEdge(g,'B','C');
    g.show(g);

    return 0;
}

template <typename T>
void graph<T> :: addEdge ( graph<T>& g , const T& v1 , const T& v2)
{
    pair<map<char, int>::iterator, bool> ret;
      ret = g.vtxMap.insert( pair<char,int>('v1',index));
      if(ret.second )         // if() condition is true , means node
      {                       // gets inserted successfully. Now 
          index++;            // increase "index"to assign new unique
      }                       // value to new node.

      ret = g.vtxMap.insert( std::pair<char,int>('v2',index));
      if(ret.second)
      {
        index++;
      }

}
template<typename T>
 void graph<T> :: show( graph<T>& g)
    {
       for( g.iter = g.vtxMap.begin(); g.iter != g.vtxMap.end(); g.iter++)
         {
             cout<< (*(g.iter)).first <<" - >" << (*(g.iter)).second <<endl;
         }
    }

输出:

  

1→ 0
  2→ 1

以上程序不是Graph的完整表示  我在初始阶段偶然发现,所以没有发布其他功能(如removeEdge(),inDegree(),outDegree(),getNeighbor()等...)
通过查看输出,似乎程序只执行第一个输入

g.addEdge(g,'A','B)     

我期待输出为

  

A - &gt; 0
  B - &gt; 1
  C - &gt; 2
  D - &gt; 3

表示只要有新节点,就应该在vtxMap中插入一个唯一值(即索引)。如果节点已经存在,则不应插入(因为地图不接受重复) 哪里错了?

1 个答案:

答案 0 :(得分:1)

插入边缘时,请使用v1代替'v1'

 template <typename T>
    void graph<T> :: addEdge ( graph<T>& g , const T& v1 , const T& v2)
    {
        pair<map<char, int>::iterator, bool> ret;
          ret = g.vtxMap.insert( pair<char,int>(v1,index));
          if(ret.second )         // if() condition is true , means node
          {                       // gets inserted successfully. Now 
              index++;            // increase "index"to assign new unique
          }                       // value to new node.

      ret = g.vtxMap.insert( std::pair<char,int>(v2,index));
      if(ret.second)
      {
        index++;
      }

}

输出:

enter image description here