I am starting to learn binary trees in cpp and dynamically allocated memories; thus to initialize a struct I do this
struct node{
int val;
node* left;
node* right;
};
//Initialize:
node* root = new node;
root->val = 7;
root->left = NULL;
root->right = NULL;
I would like to know if there is a better way to set the struct values without writing the last three lines of code. I saw on some web pages that they do this:
int* n = new int(6);
Thanks!
You can write a custom constructor:
struct node{
int val;
node* left;
node* right;
node(int);
};
node::node(int _v){
this->val = _v;
this->left = this->right = nullptr;
}
node *root = new node(6); // Works as you want
Or use member initializer list, which looks simpler:
struct node{
int val;
node* left;
node* right;
node(int _v) : val(_v), left(nullptr), right(nullptr) {};
};
Don't forget the braces after the list.
In addition to iBug's answer about using a constructor, if your object is a Plain Old Data type you can use aggregate initialisation to construct it using an initialiser-list, in the following manner, which avoids needing to define your own constructor at all:
node root = {7, nullptr, nullptr};
Or if you're allocating on the heap as you are doing:
node* root = new node{7, nullptr, nullptr};
You can have a look at this page on aggregate initialization for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With