Re: map (associative array) loses values?
<jeroenvlek@gmail.com> wrote in message
news:1189527328.279612.21880@19g2000hsx.googlegroups.com...
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?
Just because you need the map somewhere else doesn't mean you should new it.
The standard containers are actually quite small in and of themselves. If
you need the map somewhere else, you are passing the pointer to it, correct?
So just pass the pointer, or better yet, a reference to it. Creating the
map in the function is not the best method.
Consider this untested code:
class SearchText
{
public:
std::map<std::string, int>& countWords();
private:
std::map<std::string, int> table;
}
std::map<std::string, int>& SearchText::countWords()
{
table["aap"] = 1;
table["noot"] = 2;
return table;
}
int main()
{
try
{
SearchText text("test.txt");
std::map<std::string, int>& table = text.countWords();
std::cout << table["aap"] << "\n" << table["noot"] << std::endl;
}
catch(int ex )
{
std::cout << "Could not open file" << std::endl;
}
}
This is just trying to show that you don't have to new everything, in fact,
you shouldn't when you don't have to.