[prev in list] [next in list] [prev in thread] [next in thread]
List: kde-devel
Subject: Re: Doubt about STL hash_map
From: David Kamphausen <david.kamphausen () web ! de>
Date: 2003-04-24 7:21:02
[Download RAW message or body]
[Attachment #2 (multipart/signed)]
Hi!
The STL works :-)
Your local variable s is used to store the information of the key in the
hash_map. So every time you store something the old key gets overwritten.
Mind that hash_map doesn't make any copies of your pointers. Try using string
instead of const char* - it is easier to use and your example there's no real
overhead with this.
David Kamphausen
Am Mittwoch, 23. April 2003 23:34 schrieb andre-kde:
> The first program.
> In this program i just change the value of the variable 's' and
> the program doesn't works. See the code bellow:
>
> #include <hash_map>
> #include <iostream>
> #include <cstring>
> #include <stdio.h>
>
> struct eqstr
> {
> bool operator()(const char* s1, const char* s2) const
> {
> return strcmp(s1, s2) == 0;
> }
> };
>
> int main()
> {
> hash_map<const char*, int, hash<const char*>, eqstr> h;
>
> char s[16];
> for (int i = 0; i < 2; i++) {
> for (int j = 0; j < 1000; j++) {
> sprintf(s, "%d", j);
with j>0: old values of the keys are overwritten
> if (i == 0)
> h[s] = j;
the pointer to s[0] is used as key.
> else {
> if (h[s] != j)
> cout << "h[" << s << "] -> " << h[s] << endl;
> }
> }
> }
> }
>
> The second program.
> In this program i change the address of the variable 's' and the
> program works well. See the code bellow:
>
> #include <hash_map>
> #include <iostream>
> #include <cstring>
> #include <stdio.h>
>
> struct eqstr
> {
> bool operator()(const char* s1, const char* s2) const
> {
> return strcmp(s1, s2) == 0;
> }
> };
>
> int main()
> {
> hash_map<const char*, int, hash<const char*>, eqstr> h;
>
> char *s;
> for (int i = 0; i < 2; i++) {
> for (int j = 0; j < 1000; j++) {
> s = new char[16];
> sprintf(s, "%d", j);
// nothing gets overwritten because s points to a new memory position
> if (i == 0)
> h[s] = j;
> else {
> if (h[s] != j)
> cout << "h[" << s << "] -> " << h[s] << endl;
> }
> }
> }
> }
--
David Kamphausen
david.kamphausen@web.de
[Attachment #5 (application/pgp-signature)]
>> Visit http://mail.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic