存储节点顺序未知的图
在向量中存储节点顺序未知的图的最佳方法是什么?例如,我有一个未知顺序的节点,如 35,23,89,200,12,89,569 等...我想以这样的方式存储它们,即内存不会浪费,并且如果在恒定时间内可以有效地访问节点会很棒的。可能某些哈希函数可以工作,但如果有一个可以区分节点,请告诉我,或者是否有任何其他方法。
谢谢
What is the best approach to store the graph with unknown order of nodes in a vector. For example i have node coming in an unknown order like 35,23,89,200,12,89,569 etc... I want to store them in such a way that the memory is not wasted and the nodes are accessed efficiently if in constant time then it will be great. May be some hash function will work but if there is one that can distinguish the nodes please tell me or if there is any other approach for that.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想到的最简单的解决方案是将它们按顺序插入到向量中,并创建一个
map
将它们的值映射到它们的索引。在您的示例中:
现在,将节点
i
访问为vector[map[i]]
编辑:
第二种可能性是使用
set
而不是vector
来保存元素,但它可能并不总是理想的[set没有重复项,并且不会包含元素按照您插入的顺序排列],但请考虑它是否适合您。Simplest solution I think of is just insert them to your vector in order, and create a
map<int,int>
to map from their values to their indexes.In your example:
now, access the node
i
asvector[map[i]]
EDIT:
A second possibility will be to use a
set
instead ofvector
to hold elements, but it might not always be desired [set has no duplicates, and will no contain elements in the order you inserted them], but consider if it suits you.