Re: Template to insert into a map? Is this really necessary?
On Jul 7, 12:57 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
"James Kanze" <james.ka...@gmail.com> wrote in message
news:1183645844.237936.58870@q69g2000hsb.googlegroups.com...
On Jul 5, 2:49 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
I'm working on a program, and at one time I find it
necessary to load classes into a map. Now, these classes
don't have default constructors, so I can't retrieve them
using MyMap[MyKey].
So I wound up with a real ugly line:
DropdownBox& ThisBox = (Dropdowns.insert( Dropdowns.begin(),
std::make_pair<std::string, DropdownBox>( "RoteDots", DropdownBox(
Parent,
IDC_RoteDots ) ) ))->second;
Just curious, but why the iterator argument? It's only a hint,
and only helps if the insertion occurs immediately in front of
it---in this case, if the new element will be the first element.
If you don't give an iterator as the first parameter, a
different .insert is called which returns a value instead of
an iterator. I needed the iterator, so gave it an iterator.
The "value type" returned is an std::pair, with the iterator as
first element. You still get the iterator.
Most of the type, I'll have the map typedef'ed, and use its
value type:
typedef std::map< std::string, DropdownBox >
DDBoxMap ;
// ...
DropdownBox& thisBox = dropdowns.insert(
DDBoxMap::value_type(
"RoteDots",
DropdownBox( Parent,
IDC_RoteDots ) )
.first->second ;
Of course, most of the time, I'll also want to know if the
insertion succeeded.
Most of the time I would too. In this particular case, I
didn't care. I didn't even really care what iterator it gave
me with as a result. I knew they were unique values.
In which case, you can always assert that the second element of
the pair returned is true. (Or just ignore it.)
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34