私はDijkstra's AlgorithmをC++で解決しています。私はそれを隣接関係リストを使って実装しました。別のクラスを作成するためにnewを使用するか使用しないか
私はnode
のクラス、minHeap
のクラス、Graph
のクラスを持っています。
class node
{
int vertex,weight;
node *next;
friend class Graph;
friend class minHeap;
public:
node();
node(int,int);
};
node::node(){
vertex=weight=0;
next=0;
}
node::node(int v,int wt){
vertex=v;
weight=wt;
next=0;
}
私は(フレンド機能なし)minHeap
クラスをこのように定義して、私は唯一のその関数内でオブジェクトを使用することができ、通常getDijkSP()
機能でオブジェクトを作成しますか?
class minHeap
{
node *heap;
int heapSize,capacity,*pos;
public:
minHeap(int);
void addElement(node);
node extractMin();
void minHeapify(int);
void decreaseKey(int,int);
};
minHeap::minHeap(int cap){
heap=new node[capacity=cap];
heapSize=-1;
pos=new int[cap]();
} //eliminating other methods
class Graph
{
node **adjList;
int v;
bool *visited;
public:
Graph(int);
void addEdge(int,int,int);
void removeEdge(int,int);
bool existsEdge(int,int);
void getDijkSP();
};
Graph::Graph(int vertices){
adjList=new node*[v=vertices];
for(int i=0;i<v;i++)
adjList[i]=NULL;
}
void Graph::getDijkSP(){
minHeap hp(v); //here
hp.addElement(node(0,0));
for(int i=1;i<v;i++)
hp.addElement(node(i,INT_MAX));
while(!hp.isempty()){
node temp=hp.extractMin();
cout<<temp.vertex<<" "<<temp.weight<<endl;
for(node *current=adjList[temp.vertex];current;current=current->next)
hp.decreaseKey(current->vertex,current->weight+temp.weight);
}
}
(OR)私は新しいキーワードを使用してminHeap
クラスのオブジェクトを作成できるように、私は、友人の機能を持つminHeap
クラスを定義していますか? (そして、これは私が、他の機能のすべての機能でそれを使用することができるように、私は、Graph
クラスのスコープ内minHeap
オブジェクトを定義するのに役立ちます。)私はthis読み、他のいくつかのいる
class minHeap
{
node *heap;
int heapSize,capacity,*pos;
friend class Graph; //say like this
public:
minHeap(int);
void addElement(node);
node extractMin();
void minHeapify(int);
void decreaseKey(int,int);
};
minHeap::minHeap(int cap){
heap=new node[capacity=cap]();
heapSize=-1;
pos=new int[cap]();
}
class Graph
{
node **adjList;
int v;
bool *visited;
minHeap *hp; //and do this
public:
Graph(int);
void addEdge(int,int,int);
void removeEdge(int,int);
bool existsEdge(int,int);
void getDijkSP();
};
Graph::Graph(int vertices){
adjList=new node*[v=vertices];
for(int i=0;i<v;i++)
adjList[i]=NULL;
hp=new minHeap(v); //dynamic allocation
}
void Graph::getDijkSP(){
hp->addElement(node(0,0));
for(int i=1;i<v;i++)
hp->addElement(node(i,INT_MAX));
while(!hp->isempty()){
node temp=hp->extractMin();
cout<<temp.vertex<<" "<<temp.weight<<endl;
for(node *current=adjList[temp.vertex];current;current=current->next)
hp->decreaseKey(current->vertex,current->weight+temp.weight);
}
}
そのような種類の質問の両方の方法の利点、欠点、および適切性を知りたいと思っています。
私はクラスをより明確にするためにコンストラクタを提供しました。
オブジェクトを割り当てるために 'new'を使うつもりならば、おそらくそうではないはずですが、そのようなオブジェクトごとに' delete'するデストラクタを追加する必要があります。 –
はい。追加しないと申し訳ありませんが、そこにいるとしましょう。データ構造を定義するクラスを、問題を解決するようなより大きなクラスにリンクする方法を知りたいので、問題のデータ構造を使用することができます。問題に複数のデータ構造が必要な場合はどうなりますか? ..私はそのような問題の構造を定義するための最良の方法を知りたいだけです。 – revanthc97