c++ - Graph 的 map 表示

标签 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 -> 0
B -> 1
C -> 2
D -> 3

意味着每当有一个新节点时,它应该被插入到 vtxMap 中并具有唯一的值(即 index )。如果节点已经存在,则不应插入(因为 map 不接受重复项)
我哪里错了??

最佳答案

插入边时,使用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

关于c++ - Graph 的 map 表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780071/

相关文章:

c++ - 数组指针数组的析构函数

c++ - std::vector of movable-only lambdas,这可能吗?

c++ - <algorithm> 中的 Visual Studio 2008 错误? includes 算法似乎无意中交换了第 3795 行迭代器的顺序

c++ - 无法访问 C++ std::set 中对象的非常量成员函数

c++ - 如何在 std::unique_ptr 的 std::vector 上使用remove_if?

c++ - QTextEdit。如何手动选择文本?

c++ - 自动引用 vector ?

c++ - 如何在不构造 key_type 对象的情况下在 std::multiset 中进行二进制搜索?

访问成员 STL 映射时的 C++ 段错误

c++ - 如何在不同线程中同时运行多个 QDialogs?