首页 > 解决方案 > 指向其他许多对象的有效成员指针

问题描述

假设我有一个图,每个节点可能包含其他节点的值。假设计算该值的复杂性相当高( ~O(n^4) )。因此,我想存储为每个关系计算的值。我在 C++ 方面相当新,所以这就是我得到的(不包括构造函数等,为了简单起见使用 struct):

struct Node{
    long id_;
    const std::shared_ptr<Node> left_;
    const std::shared_ptr<Node> right_;
    const std::shared_ptr<Node> up_;
    const std::shared_ptr<Node> down_;
    std::unordered_map<std::shared_ptr<Node>, double> otherValues;
    
    double calculate(Node other);   // do math based on neighboring nodes
};

因此,假设节点很少被删除但经常被添加,我想知道这是否是正确的方法?最初,我打算这样做,weak_ptr因为所有节点也都存储在其他地方,但随后我必须在shared_ptr查找下一个节点的任何时候进行转换(一直如此)。我读过的这本书以及大多数文章都指出,如果可能的话,应该使用智能指针,但我想知道原始指针是否是这里更有效的方法。但是我不知道如何在这里实现这些,同时仍然安全。

任何建议将不胜感激!

编辑:我更改了otherValues以反映示例的其余部分。

标签: c++performanceclasssmart-pointersmember

解决方案


很多时候,你想通过坐标而不是相对的来访问节点在这种情况下你会得到这样的东西:

class Coordinate {
   int x, y;
};
enum Direction4 {
   Left, Up, Right, Down
};
Coordinate operator+(Coordinate, Direction4);

class Node {
    Graph* graph;
    Coordinate coordinate;
    Node* getAdjacent(Direction4 dir);
    double calculate(Node other);
};

class Graph {
    std::unordered_set<Coordinate, Node> nodes;
};

Node* Node::getAdjacent(Direction4 dir) {
    Coordinate coord = coordinate + dir;
    auto it = graph->nodes.find(coord);
    if (it == graph->nodes.end()) return nullptr;
    return &(it->second);
}

您可以通过坐标立即访问任何节点。图拥有节点,节点不拥有彼此。事实上,节点甚至不相互引用。这意味着我根本不必担心内存泄漏、重新分配或死指针。所有这些问题都已经完全消失了。


推荐阅读