Miles Smith
Miles Smith

Reputation: 47

Class that has the member Vector of its own members

I'm trying to write a Neural Network. I've done it before in other languages, and using matrices libraries; however, I wanted to make it on my own, to better understand them. However I have run into a problem with my classes.

I am doing this in C++.

I have a class called ANN. It has a vector of layers. layers are a class called Node. However, within node I want to access the previous layer of nodes, so I can calculate this node's values.

I know if I have a class, and I want one of its members to be of itself it has to be a pointer. ex.

class Node{
public:
    // Public methods/members here
private:
    Node *previousNode;
}

However, this is not what I want. I want *previousNode to be ancestor of nodes

here is an example of what I want

class Node{
public:
    //Public functions/members here
private:
    vector <Node*> previousLayer;
}

Now I've heard in this situation it would be better to use a smart pointer. I don't exactly know what that is, I know it is basically a wrapper for pointers that manage them. I also thought the main reason smart pointers were used is because some pointers get left NULL or not deleted after use, but I did not think that would really matter seeing as the scope of this class could only possible end when the program ends.

My question is how would I implement a vector of pointers to the class the vector is in.

Upvotes: 1

Views: 136

Answers (2)

Chris
Chris

Reputation: 615

If I'm interpreting your question correctly, it sounds like you want each instance of Node to contain a list of pointers to other Node objects that it is connected to.

What you have written is fine, but as you say, it could make for safer code to use std::shared_ptr.

class Node{
 public:
     //Public functions/members here
 private:
     vector <shared_ptr<Node>> previousLayer;
 }

You should allocate your nodes with std::make_shared and they will persist in memory for as long as they are used (no need for new or delete.)

Upvotes: 2

jstar
jstar

Reputation: 26

std::vector <Node*> previousLayer;

if you want to handle all the element in the vector, using the iterator:

for (auto it = previousLayer.begin(); it != previousLayer.end(); ++it)
{
    Node* node = *it;
    handle(node);
}

// Note: you can using "for (std::vector<Node*>::iterator it = previousLayer.begin(); it != previousLayer.end(); ++it)" instead.

if you only want to access one element, using the operator []:

Node* node = previousLayer[n];
handle(node);
// but be careful, don't make the n out of range. that means n must be "0 <= n < previousLayer.size()"

vector introduction: http://en.cppreference.com/w/cpp/container/vector

Upvotes: 0

Related Questions