I'm having some issues understanding a problem I've mentioned in the comments below:
class Node {
public:
Node(int value): value(value), neighbors() {}
int value;
std::vector<std::shared_ptr<Node>> neighbors;
};
std::vector<Node> nodes;
nodes.reserve(50);
for(int j = 0 ; j < 50; ++j) {
nodes.push_back(Node(j));
}
for(int j = 1 ; j < 25; ++j) {
nodes.at(0).neighbors.push_back(std::make_shared<Node>(nodes.at(j)));
}
//The following line is copying nodes.at(0) instead of just
//copying a reference to nodes.at(0). Why?
nodes.at(15).neighbors.push_back(std::make_shared<Node>(nodes.at(0)));
for(int j = 25 ; j < 50; ++j) {
nodes.at(0).neighbors.push_back(std::make_shared<Node>(nodes.at(j)));
}
std::cout << nodes.at(15).neighbors.at(0).neighbors.size();
//Prints out 24
std::cout << nodes.at(0).neighbors.size();
//Prints out 49
Why is the following line copying nodes.at(0) (which returns a reference to the first element of nodes vector) instead of storing a reference to it?
nodes.at(15).neighbors.push_back(std::make_shared<Node>(nodes.at(0)));