Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C++
Initializing a map...
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="James Kanze, post: 3451025"] I think there will be in the next version of the standard. (I know that there was a proposal for extended initializers, but I'm not sure what the current status of the proposal was.) This is the only way to create a const map. I often find it worthwhile to define a special structure for this, something along the lines of: typedef std::map< std::string, double > Map ; struct MapInit { char const* key ; double value ; operator Map::value_type() const { return Map::value_type( std::string( key ), value ) ; } } ; Partially for historical reasons: earlier Microsoft compilers had problems with agglomerate initialization if the components of the agglomerate weren't agglomerates themselves. But having gotten into the habit of it... It's still worth considering if the initialization array is in a separate compilation unit (e.g. because it is machine generated), since you can arrange for the table of MapInit to use static initialization, thus avoiding all order of initialization issues. Not recommended for big maps in the middle of a tight loop:-). Neither of the above allow the map to be const, of course. Another possibility is to derive, with the derived class providing a constructor which populates the map (and nothing else). Again, this allows the map to be const. It also works with older implementations, which didn't always support the two iterator form of the constructor (because they were designed around compilers which didn't support member templates). So you have something like: class MyMap : public std::map< type1, type2 > { public: MyMap() ; } ; MyMap::MyMap() { insert( value_type( key1, value1 ) ) ; insert( value_type( key2, value2 ) ) ; // ... } (Again, you could probably arrange for the constructor to be machine generated.) Concerning the "machine generated": if your map has so few entries that you can consider writing them out by hand, you're likely better off just using a C style array and std::find_if. (For a const map, of course. But I can't remember a case where I wanted to initialize the map's contents on creation, but didn't want it const, although I'm sure that they do exist.) [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C++
Initializing a map...
Top