保留存储在STL容器中的指针所指向的值(unordered_map)

Preserving the values that the pointers stored in STL container point to (unordered_map)

本文关键字:unordered map 指针 STL 存储 保留      更新时间:2023-10-16

我有如下的数据结构

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;  

我想做的是,一旦我计算出某个节点的所有顶点的所有路径/成本,并将其存储在吸引列表容器中,我就想重用这些信息,这样来自该源节点的后续路由调用就会更快。为此,我想保存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中存储的指针发生更改时,从中生成的所有副本都无效。如何永久存储它们?这个容器中的复制是如何完成的?如有必要,如何重载赋值运算符?这可能吗?我可以对我的数据结构和容器做一些细微的更改,但不会做太多。

抱歉发了这么长的邮件。提前谢谢。

attractionList* newList = new attractionList(); //make a new object to store old state
newList = &attrList;     //copy values from old state

这个问题很明显。当指针存储在attrList更改了所有由它生成的副本都是无效的。

您没有复制。您在堆上分配了一个新的空列表,然后丢弃了指向它的指针,并存储了一个指向现有列表的指针。

我想你的意思是:

attractionList newList = attrList;

但我还没有查看您的其余代码,所以这可能不是一个完整的解决方案。

关于您的评论:

如果你也需要复制景点,那么你需要一个地方来存放它们。由于你没有说明如何存储原件,我无法告诉你在哪里存储副本,但其余的代码将是这样的:

attractionList newList;
for (attractionList::iterator it = attrList.begin(); it != attrList.end(); ++it) {
attraction *newNode = /* copy of *(it->second) */;
newList.insert(make_pair(it->first, newNode));
}