c++ - 指向其他许多对象的有效成员指针
问题描述
假设我有一个图,每个节点可能包含其他节点的值。假设计算该值的复杂性相当高( ~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以反映示例的其余部分。
解决方案
很多时候,你想通过坐标而不是相对的来访问节点,在这种情况下你会得到这样的东西:
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);
}
您可以通过坐标立即访问任何节点。图拥有节点,节点不拥有彼此。事实上,节点甚至不相互引用。这意味着我根本不必担心内存泄漏、重新分配或死指针。所有这些问题都已经完全消失了。
推荐阅读
- php - Wordpress + Elementor:PDF 中的西里尔字母
- mvvm - SwiftUI @Binding 使用不同的导航项在推送/弹出时重新加载
- php - php unzip 在 Linux 上将文件夹名称视为文件名
- jenkins - 如何使用格式化 HTML 从 Jenkins Active Choice 参数获取用户输入
- swift - 我需要帮助将 UITextField 从字符串转换为 Int
- javascript - 如何根据javascript中的条件对现有数组对象中的值求和
- java - 如何在 VS Code 远程容器中设置 java.home 路径
- wso2 - 自定义 WSO2 API Manager 3.1.0 管理控制台的界面
- sef - 如何阅读零件
- angular-reactive-forms - 无法绑定到“formGroup”,因为在使用 SharedModule 时它不是“form”的已知属性