如何使用std :: map在C中构建树结构
发布时间:2020-12-16 06:59:58 所属栏目:百科 来源:网络整理
导读:我试图在C中编写一种树形结构.每棵树都有树枝和树叶.分支可以包含其他分支以及叶子. 现在我的实现要求每个分支和叶子具有不同的功能.所以举个例子. 采取树结构 Root | | Branch1 Branch2 Branch3 | | | Leaf1 Leaf2 Branch4 Now Each Leaf and branch has a
我试图在C中编写一种树形结构.每棵树都有树枝和树叶.分支可以包含其他分支以及叶子.
现在我的实现要求每个分支和叶子具有不同的功能.所以举个例子. 采取树结构 Root | | Branch1 Branch2 Branch3 | | | Leaf1 Leaf2 Branch4
我最初试图实现复合设计模式.但这意味着我会拥有和叶子一样多的课程.但由于我有大量的树叶和树枝,我想避免创造更多的课程.我意识到这是一个不寻常的情况,但希望有人能在这方面帮助我.在不创建太多类的情况下实现此树的最佳方法是什么. 我也使用map 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; } 解决方法
具有相同签名的不同功能仍具有相同的类型.即使函数完全不相关,也可以使用void *(类型擦除)来存储随机数据的树,然后在到达叶节点后将类型转换回已知的实际类型.
struct node { void (*fptr)(); // pointer to any function taking no args,no return void *data; // pointer to anything,need to cast before using }; void f() { std::cout << "hello"; } void g() { std::cout << "world"; } node a = { f,f }; node b = { g,g }; a.fptr(); static_cast< void (*)() >( b.data )(); 您还可以将虚方法与继承一起使用,并将指针存储在树中的基类类型中.这取决于节点究竟是什么. 这些都与它进入图表的事实无关. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |