Re: map (associative array) loses values?
jeroenvlek@gmail.com wrote:
Hi there,
I've never done this before, so I don't know about any layout
possibilities. My apologies :)
The problem is this:
I've written a function:
map<const char*, int> *SearchText::countWords()
{
map<const char*, int> *table = new map<const char*, int>;
(*table)["aap"] = 1;
(*table)["noot"] = 2;
cout << (*table)["aap"] << endl;
cout << (*table)["noot"] << endl;
return table;
}
Which I want to use like this:
try {
SearchText *text = new SearchText("test.txt");
map<const char*, int> *table = text->countWords();
cout << (*table)["aap"] << endl;
cout << (*table)["noot"] << endl;
}
catch(int ex) {
cout << "Could not open file." << endl;
}
However, I get the following output:
1
2
0
0
Meaning that the first two output statements (in the function itself)
do their job and the second two do not.
I guess it's some sort of allocation problem,
nope.
The problem is the data structure
map< char*, ... >
Note that this will (a) store pointers to char and (b) compare those
pointers (not the strings pointed to) to identify keys. Also note that two
different string literals "aap" are _not_ guaranteed to be represented by
the same char*. That is why you don't find the recorded entries.
but what could I do different?
Use map< std::string, ... > instead. That will store and compare values.
I guess I could use maybe malloc or calloc, but shouldn't this be also
possible with new?
On that note: why do you do dynamic allocation of the map anyway? Your code
is littered with new() for no reason (and it misses the corresponding
delete statements, too).
BTW making table static in the function didn't help.
It is not expected to.
Best
Kai-Uwe Bux