0

Just a quick C++ question. I've been trying to save a node inside a vector to the right child of a node.

For example,

I have a struct called node that has a pointer leading to a left child and a right child. So:

struct node{
     node *left;
     node *right;
};

My vector of nodes,

vector<node> nodeVec;

consists of nodes as well.

The goal is to then take a node out of my vector and save as the right and left child of a new node.

So:

node *tree = new node();
tree->left = *nodeVec.at(0);
tree->right = *nodeVec.at(1);

But it throws an error saying that it doesn't recognize the '*' operator. Trying just

tree->left = nodeVec.at(0)

It says that I can't convert a node to a node*.

But if I use,

tree->left = &nodeVec.at(0)

It succesfully saves the address inside my left child. I took a look at a couple of sites and answers and I think the one found here,

Dereference vector pointer to access element,

might've been the most relevant. I gave it a shot and threw so many errors, I didn't quite understand.

In short, from what i've read, I need to dereference the node inside my vector. But if it doesn't accept the '*' operator, how would one do that?

Thanks in advance!

Community
  • 1
  • 1
OrionDev
  • 3
  • 1
  • 3

1 Answers1

0

You can access nodes in the vector like this:

node* p_left = nodeDev.at(0).left;

node copy_constructed_node(*(nodeDev.at(0).right));

You can also use your tree:

node* p_left = tree->left;  // your code set this to &nodeVec[0]

More generally, I suggest you do some background reading on pointers (maybe here), or - better yet - consider whether a Standard container will satisfy your needs - e.g. std::map (tutorial here).

Community
  • 1
  • 1
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252