Let's say I have a graph and each node may contain a value for other nodes. Let's also say that the complexity to calculate that value is rather high ( ~O(n^4) ). Consequently, I would like to store the values that have been calculated for each relation. I'm rather new at C++, so this is what I got (constructors, etc. not included and using struct for simplicity):
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
};
So assuming that nodes very rarely get removed but are added frequently, I wonder if this is the right approach? Initially, I was going for weak_ptr
since all the nodes are stored somewhere else as well, but then I'd have to cast to shared_ptr
anytime I look up the next nodes (which is all the time). The book, as well as most articles, that I have read state that one should use smart pointers if possible, but I wonder if raw pointers are the more efficient approach here. But then I'd have no idea how to implement these here while still being safe.
Any advice would be greatly appreciated!
Edit: I've changed otherValues to reflect the rest of the example.