help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: problems with stl map iterators


From: Thomas Maeder
Subject: Re: problems with stl map iterators
Date: Tue, 19 Apr 2005 19:07:27 +0200
User-agent: Gnus/5.1006 (Gnus v5.10.6) XEmacs/21.4 (Jumbo Shrimp, linux)

Christian Christmann <plfriko@yahoo.de> writes:

> class HashTable 
> { 
>     map<int, void*> nhash; 
>     map<int, void*> getNhash(); 

Consider using a typedef next time.


> ... 
> } 
> ---------- 
>
> My hashtable.cpp: 
>
> map<int, void*> HashTable::getNhash() 
> { 
>   return nhash; 
> } 
>
> void HashTable::Insert(int ky,void* entr) 
> { 
>   nhash.insert(pair<int, void*>(ky, entr)); 
> } 
> ... 
>
> ---------- 
>
> In another class I use this hashtable: 
>
> HashTable lNodes; 
> const std::map<int, void*>::const_iterator begin = lNodes.getNhash().begin(); 
> const std::map<int, void*>::const_iterator end = lNodes.getNhash().end(); 

getNhash() returns its result by value. begin and end are thus
unrelated; in particular, end is not reachable from begin.


> std::map<int, void*>::const_iterator iter = begin; 
>
> cout << "Size: " << lNodes.getNhash().size() << endl; 
>     while (iter != end) 
>     { 
>       cout << "Key: " << iter->first << endl; 
>       ++iter; 
>     } 
>
>
>
> The output: 
>
> Size: 3 
> Key: 0x80a2de0 

Bad luck. With more luck, the iteration would have continued until
iter->first would have attempted to access inaccessible memory, which
would have caused the program to crash.

If you change getNhash()'s return value to map<int, void*> &, you
should get the results you expect.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]