Hi,
can anyone tell me why i can't clean up the memory,
and maybe a small solution.
I'm allocing memory with strdup for each key,
but I cant figure out how to erase the key with free.
Before anyone starts talking about mixing c++ and c,
I know it's generally a bad idea but std::strings are to slow.
#include<iostream>
#include<cstring> //for cstring functions
#include<map> //associative array
#include<cstdlib>
struct cmp_str {
bool operator()(const char *a,const char *b) {
return std::strcmp(a, b) < 0;
}
};
void printMap(std::map<const char*,int,cmp_str> &asso){
for(std::map<const char*,int>::const_iterator it = asso.begin(); it != asso.end(); ++it){
printf("%s:\t %d\n",it->first,it->second);
}
}
std::map<const char*,int,cmp_str> build(){
std::map<const char*, int,cmp_str> asso;
const char *text = "does is work";
char *tmp=NULL;
tmp = strtok(strdup(text)," \t");
while(tmp!=NULL){
asso[strdup(tmp)] = 1;
tmp=strtok(NULL," \t");
}
return asso;
}
void cleanup(std::map<const char*,int,cmp_str> &asso){
std::map<const char*,int,cmp_str>::iterator it;
asso.erase(asso.begin(),asso.end());
}
int main(int argc, char** argv){
std::map <const char*, int,cmp_str> asso = build();
printMap(asso);
printf("should return 1: %d\n",asso["is"]);
printf("should return 0: %d\n",asso["0"]);
cleanup(asso);
return 0;
}