On 19 Dec 2006 07:52:53 -0800 in comp.lang.c++, "utab"
<umut.tabak@gmail.comwrote,
Quote:
>but I wondered why I could not define and
>initiliaze outside the function block. As
>
>word_map["try"].insert(make_pair("try",1));
>
>and the entries outside any of the functions.
The above has the form of an executable statement. You can't have any
executable statements outside of a block; only declarations.
The thing that makes it difficult is that you cannot write a constant of
type std::map<anythingdirectly (unlike simple arrays of simple types.)
The compiler doesn't know how to build it. You have to take a trip
through the std::map constructor for that to happen.
If you wished, you could write the definition of your static as:
map< string , map<string, int X::word_map = X::initial_map();
where X::initial_map() was a static function that returns a big honking
value of the matching std::map<type, that gets copied to X::word_map.
This would be doing a lot of extra copying during initialization time,
so it's probably not the best choice. I mention it only for the sake of
comparison.
I guess the best choice for you might be to use a "singleton" pattern.
To do that, make X::word_map() a function that returns a reference to
the static map, and call it wherever you access the map. The first time
through, X::word_map() does all the work of building the map; thereafter
it just returns a reference to the existing map. And of course, it can
use all the executable statements it needs to do that, even reading
values from a file or whatever.
By the way, I cannot guess any reason why the value_type of your map is
another map, so I think you are probably making things a heck of a lot
more complicated than you really need to by doing that.