Re: map (associative array) loses values?
jeroenvlek@gmail.com wrote:
On Sep 11, 5:59 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
<cut>
Best
Kai-Uwe Bux
ah, ok. <string, int> works like a charm! :)
I'm using new, because I need the table somewhere else. The try/catch
is in my main, while the function resides in the SearchText class. The
delete statements are there, I just didn't post them ;)
Ofcourse I'm just a c++ newbie (this is my first program actually), so
what would you do different?
I would start with something like
map<const std::string, int> SearchText::countWords()
{
map<std::string, int> result;
result["aap"] = 1;
result["noot"] = 2;
cout << result["aap"] << endl;
cout << result["noot"] << endl;
return result;
}
and later
try {
SearchText text ("test.txt");
map<const std::string, int> table = text->countWords(); // *
cout << table["aap"] << endl;
cout << table["noot"] << endl;
}
catch(int ex) {
cout << "Could not open file." << endl;
}
That is, on the first try, I would leave it to the compiler to optimize away
the apparent copy-construction in line (*). If profiling shows that the
compiler does not eliminate the copy-constructor calls _and_ that there is
a need to improve performance, I might change the program:
void SearchText::countWords( map<std::string, int> & result ) {
result["aap"] = 1;
result["noot"] = 2;
cout << result["aap"] << endl;
cout << result["noot"] << endl;
}
....
try {
SearchText text ("test.txt");
map<const std::string, int> table;
text->countWords( table );
cout << table["aap"] << endl;
cout << table["noot"] << endl;
}
catch(int ex) {
cout << "Could not open file." << endl;
}
or I might resort to swap() tricks (faking move semantics):
map<const std::string, int> SearchText::countWords()
{
map<std::string, int> result;
result["aap"] = 1;
result["noot"] = 2;
cout << result["aap"] << endl;
cout << result["noot"] << endl;
return result;
}
....
try {
SearchText text ("test.txt");
map<const std::string, int> table;
text->countWords().swap( table );
cout << table["aap"] << endl;
cout << table["noot"] << endl;
}
catch(int ex) {
cout << "Could not open file." << endl;
}
Also: I would have the constructor of SearchText throw something more
meaningfull than an int.
Best
Kai-Uwe Bux