When I'm learning data structure at the binomial heap, I read Weiss's code implementation. Some code as follow:
node implementation and deleteMin algorithm are like:
template<typename Comparable>
struct BinomialNode
{
Comparable element;
BinomialNode *leftChild;
BinomialNode *nextSibling;
};
void deleteMin( Comparable & minItem )
{
int minIndex = findMinIndex( );
minItem = theTrees[ minIndex ]->element;
BinomialNode *oldRoot = theTrees[ minIndex ];
BinomialNode *deletedTree = oldRoot->leftChild;
delete oldRoot;
}
But I'm confused by the "Comparable & minItem". As we see, the "minItem" saves the element. But soon the "oldRoot" has been deleted! The "element" member is inside of the "oldRoot"! Can someone tell me the principle of the status...
I also made some other tests.
struct Node{
int i;
Node * next;
Node(int i, Node* next = nullptr): i(i), next(next){}
};
void getInt(int & i){
int * p = new int(3);
i = *p;
delete p; //the reference can get the true value??? =>output: 3(right)
}
void getInt(int * &i){
int * p = new int(3);
i = p;
delete p; //pointer can't get the real number because of deletion => output: 6904432(wrong)
}
int main() //for test
{
Node* child = new Node(3);
Node* root = new Node(1, child);
int i;
getInt(i);
cout << i << endl;
int * m;
getInt(m);
cout << *m;
}
I've learnt about the bottom implementation of the reference & is the point *. But why & can get the real value... I feel confused. Thx!!