唉,STL 函数和容器并不总是如您所愿。这是两个通用版本,第一个更像您上面的代码:
template<class Map>
inline typename Map::iterator ForceInsert1(
Map& m,
const typename Map::key_type& k,
const typename Map::data_type& d )
{
typename Map::iterator it = m.insert(
typename Map::value_type( k, d ) ).first;
it->second = d; // only necessary if the key already exists
return it;
}
template<class Map>
inline typename Map::iterator ForceInsert2(
Map& m,
const typename Map::key_type& k,
const typename Map::data_type& d )
{
typename Map::iterator it = m.find( k );
if( it != m.end() )
{
it->second = d;
}
else
{
it = m.insert( typename Map::value_type( k, d ) ).first;
}
return it;
}
typedef std::map<int, int> MyMap;
void Foo( MyMap& myMap )
{
ForceInsert1( myMap, 42, 100 );
ForceInsert2( myMap, 64, 128 );
}