【发布时间】:2013-12-22 10:48:25
【问题描述】:
我的数据结构如下
struct routing
{
int color; //white = -1, gray = 0, black = 1
unsigned int d; //distance
unsigned int pi; //previous node id
routing() : color (-1), d (UINT_MAX), pi (UINT_MAX ) {}
};
struct attraction //each node in graph is called an attraction
{
unsigned int id; //id of node
std::string name; //name
unsigned int priority; //priority
std::unordered_map<int, int> nodeMap; //destination node id, distance
routing r; //routing information
attraction() : id (0) , name(""), priority(0) {}
};
现在,我必须运行 Dijkstra 算法来找到不同节点(称为景点)之间的最短距离。我已经实现了它,它工作得很好。除了它很慢(比我需要的)。
我有一个存储节点信息的 STL 容器。我用它来执行路由。如下:
//I use unordered_map for fast access of elements.
typedef std::unordered_map<unsigned int, attraction*> attractionList;
attractionList attrList;
我想要做的是,一旦我计算出某个节点的所有顶点的所有路径/成本并将其存储在 attractionList 容器中,我想重用这些信息,所以来自该特定源节点的后续路由调用将更快。为此,我想保存 attrList 容器的状态,以便快速重用存储的信息。我正在尝试的是这样的:
//make another container whose first element is a unique source id, second element is the attractionList
std::unordered_map<unsigned int, attractionList> stateMap; (containig routing information)
attractionList* newList = new attractionList(); //make a new object to store old state
newList = &attrList; //copy values from old state
//insert in another container so that each unique source id has all routing information stored
stateMap.insert(std::pair<unsigned int, attractionList> (from, *newList));
嗯,这个问题很明显。当存储在 attrList 中的指针发生变化时,由它制作的所有副本都是无效的。如何永久存储它们?在这个容器中复制是如何完成的?如有必要,如何重载赋值运算符?这甚至可能吗?我可以对我的数据结构和容器进行细微的更改,但不会太多。
抱歉,帖子太长了。提前谢谢你。
【问题讨论】:
-
问题是你盲目地使用
new没有任何押韵或理由。newList = &attrList;是即时内存泄漏。 -
newList = &attrList; //copy values from old state— 我不认为这意味着你认为它的意思。 -
@n.m.我有点新手(一个睡眠不足的人)。所以在这种情况下,我的 newList 只会指向旧的,对吧?但是,即使我在堆栈上声明 newList,我仍然无法正确处理。
-
“I can't get it right”包含大约一点信息,不足以诊断您的问题。
-
对不起,我会澄清的。在计算与新源节点的距离之前,我需要重置 attrList 中存储的每个节点(景点*)中的路由信息。但正如我所说,我需要保留旧的路由信息。我尝试按照@Steve Jessop 的建议通过
attractionList newList = attrList;在堆栈上声明一个新列表,并将其添加到stateMap。但是当我重置 attrList 中的数据时,新“存储”列表的数据也变为 NUll/reset。 attrList 在类中声明为私有成员。
标签: c++ stl unordered-map