#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++;
}
}
输出:
关于c++ - Graph 的 map 表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780071/