C++ でツリー構造を書こうとしています。どの木にも枝と葉があるように。枝には、葉だけでなく他の枝も含めることができます。現在、私の実装では、各ブランチとリーフに異なる機能を持たせる必要があります。たとえば。ツリー構造を取る
Root
| |
Branch1 Branch2 Branch3
| | |
Leaf1 Leaf2 Branch4
各リーフとブランチには実行する関数が異なるため、Leaf1 には leaf1_func という関数があり、Leaf2 には leaf2_func があり、Branch4 には Branch4_func があります。
私は当初、複合設計パターンを実装しようとしていました。しかし、それはリーフと同じ数のクラスを持つことを意味します。しかし、葉や枝がたくさんあるので、避けたいのは、より多くのクラスを作成することです。これは異常な状況だと認識していますが、誰かがこの点で私を助けてくれることを望んでいました. あまりにも多くのクラスを作成せずにこのツリーを実装する最良の方法は何でしょうか.
私はマップ STL コンテナーを使用してデータを保存しています。このツリー実装を使用して、TSP 問題でこれを解決したいと考えています。
#include <cstdlib>
#include <iostream>
#include <map>
using namespace std;
int n=4;
int min=1, max=10;
struct graph
{
int nodes;//total no. of nodes or vertices namely cities
std::map<std::pair<int,int>, int> graphMap;//an object that links a pair of vertices
};
void directed_Graph(graph);
void directed_Graph(graph G)
{
//int n = G->nodes; //city count
int i, j;
for(i = 0; i <= n-1; i++)
{
for(j = 0; j <= n-1; j++)
{
if(i!=j)
{
G.graphMap[std::make_pair(i,j)] = (rand()%10)+1;
//cout<<G.graphMap[std::make_pair(i,j)]<<"\n";
}
else
{
G.graphMap[std::make_pair(i,j)] = 0;
}
}
}
}
int main(int argc, char** argv)
{
graph g;
g.nodes = 4;
directed_Graph(g);
return 0;
}