Re: Template to insert into a map? Is this really necessary?
"James Kanze" <james.kanze@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.
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.
[Snip the rest]
The funny thing is, after I implented this, and finished my program, I
realized I never once searched for the key. And then I realized a structure
would be better to hold the instances than a map :/ So I deleted the
template and everything associated with it.