I am trying to implement a generic tree and in the function getSizeRecursive
line 1
why cannot i use const node* &root
. Similarly, i am getting the same mistake in line 2
.The compiler is giving an error which i am not able to comprehend.
graph.cpp: In function 'int getSizeRecursive(const node*&)':
graph.cpp:56:40: error: binding reference of type 'const node*&' to 'node* const' discards qualifiers
56 | for(const node* &child : root->children) // line 2
| ^~~~~~~~
graph.cpp: In function 'int main()':
graph.cpp:69:36: error: binding reference of type 'const node*&' to 'node*' discards qualifiers
69 | cout << getSizeRecursive(t.root) << endl;
| ~~^~~~
graph.cpp:51:35: note: initializing argument 1 of 'int getSizeRecursive(const node*&)'
51 | int getSizeRecursive(const node* &root){ // line 1
| ~~~~~~~~~~~~~^~~~
[Finished in 2.9s]
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class node{
public:
int data;
vector<node*> children;
node(int val){
data = val; // this->data = data
}
~node(){
for(int i = 0 ;i<children.size();i++){
if(!children[i])
delete children[i];
}
}
};
class GenericTree{
public:
node* root; // line 3
int size;
GenericTree(vector<int> nums){
stack<node*> st;
size = 0;
for(int i = 0;i<nums.size();i++){
node *n = new node(nums[i]);
if(i == 0){
root = n;
st.push(n);
++size;
}else{
if(n->data == -1){
st.pop();
}else{
// cout << "In me" << endl;
st.top()->children.push_back(n);
st.push(n);
++size;
}
}
}
}
// tells us the number of nodes
int getSize(){
return size;
}
};
int getSizeRecursive(const node* &root){ // line 1
if(root->children.size()==0)
return 1;
int size = 0;
for(const node* &child : root->children) // line 2
size += getSizeRecursive(child);
return size+1;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
freopen("error.txt","w",stderr);
#endif
vector<int> v{10,20,-1,30,50,-1,60,-1,-1,40,-1,-1};
GenericTree t(v); // node that tree has been created
cout << t.size << endl;
cout << getSizeRecursive(t.root) << endl;
return 0;
}
What i can understand from this is that compiler is not able to bind the reference to pointer to const node
to const pointer to node
but my question is that why it is taking t.root
as const pointer to node
whereas in actual it is just a pointer to node
(see line no 3).
I am novice in c++. Any help would be appreciated.
EDIT: The reason i have used const* & root
is because i did not want to pass a copy of root to getSizeRecursive
but during that since i have passed by reference i have used const
so that this reference just only reads the root pointer and not modify it.