user defined types and std::map
hello,
i want to make a map keyed on strings represented by char* (i.e. c strings). how would i do this?
it seems that if i declare map<char*, mytype>, then the keys would be the actual pointer and not the strings the pointers point to.
example: i want this to work:
const char* str1 = "test";
const char* str2 = "test";
map<char*, mytype*> m;
m[str1] = my_data;
assert(m.find(str2) != m.end());
thank you,
-- christopher
Re: user defined types and std::map
Quote:
Originally posted by clockworks
hello,
i want to make a map keyed on strings represented by char* (i.e. c strings). how would i do this?
it seems that if i declare map<char*, mytype>, then the keys would be the actual pointer and not the strings the pointers point to.
Why not use std::string instead of char*?
Code:
#include <string>
//...
std::string str1 = "test";
std::string str2 = "test";
map<std::string, mytype> m;
m[str1] = my_data;
assert(m.find(str2) != m.end());
//...
Regards,
Paul McKenzie
Re: Re: user defined types and std::map
Quote:
Originally posted by Paul McKenzie
Why not use std::string instead of char*?
Paul McKenzie
I definitely agree with Paul on this one. Unless you are very very careful, using char *'s as index into a map will invariably lead to memory leaks. Use std:string, it's much safer and much easier to handle. There is practically no performance penalty either.
For an example of the problems see this code:
Code:
// bad code !
std::map<char *, int, StringComp> m;
char *sz;
sz = new char[2];
sz[0] = '0';
sz[1] = 0;
m[sz] = 25;
// This char * now belongs to the map,
// so you should not free it until you free the item in the map
sz = new char[2];
sz[0] = '0';
sz[1] = 0;
m[sz] = 10;
// since "0" was already a key, it is not put into the map again
// now you DO have to delete [] it.
Simply awful ;)