c++ - unexpected changes in member variables of an object -
i have code in c++:
void printheap (heap<t> &heap) { typename list< heapnode<t> >::iterator heapiterator = heap.heap.begin(); for( ; heapiterator != heap.heap.end(); ++heapiterator) { cout<<"element"<<endl; } } and definition of heap:
template <class t> class heap { public: list <heapnode<t> > heap; heapnode<t> *minvalue; binomialheap(heapnode<t> *min = 0) { minvalue = min; } t getminimumkey() { homecoming minvalue->key; } void insert(t data) { heapnode<t> tmp (data); heap.push_back(tmp); if(!minvalue || minvalue->key > tmp.key) minvalue = &tmp; } }; heapnode.cpp template
class heapnode { public: int degree; heapnode<t> *parent; list <heapnode<t> *> sons; t key; heapnode(t d, heapnode<t> *parent = 0) { key = d; this->parent = parent; grade = 0; } }; i have tried code, getting unexpected values:
binomialheap<int> heap; heap.insert(4); heap.insert(3); heap.insert(2); heap.insert(1); cout<<heap.getminimumkey() <<endl; printheap(heap); cout<<heap.getminimumkey(); the first cout prints 1 (as expected), after calling printheap, minvalue changes though did not manipulate fellow member variable (the sec cout prints weird number). why happening? shouldn't print same number, since not modifying minvalue in method?
void insert(t data) { heapnode<t> tmp (data); heap.push_back(tmp); if(!minvalue || minvalue->key > tmp.key) minvalue = &tmp; }
this code broken. create temporary object, stash pointer it. function returns, object ceases exist, pointer points nothing. when phone call getminimumkey, garbage. think wanted set minvalue point re-create of tmp pushed onto list.
c++ oop data-structures
No comments:
Post a Comment