I am trying to write a tree type structure in C ++. As in every tree there are branches and leaves. The branch may contain other branches, as well as leaves. Now my implementation requires that each branch and leaf have different functionality. For example. Take a tree structure
Root
| |
Branch1 Branch2 Branch3
| | |
Leaf1 Leaf2 Branch4
Now each leaf and branch has a different function to execute, so Leaf1 will have a function called leaf1_func, Leaf2 will have leaf2_func, Branch4 has Branch4_func.
At first I tried to implement a composite design structure. But that means that I will have as many classes as there are leaves. But since I have tons of leaves and branches, I would like to avoid creating classes. I understand that this is an unusual situation, but I hoped that someone could help me in this regard. What would be the best way to implement this tree without creating too many classes.
I use the STL container for data storage, I want to use this tree implementation to solve this problem in TSP.
#include <cstdlib>
#include <iostream>
#include <map>
using namespace std;
int n=4;
int min=1, max=10;
struct graph
{
int nodes;
std::map<std::pair<int,int>, int> graphMap;
};
void directed_Graph(graph);
void directed_Graph(graph G)
{
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;
}
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;
}
source
share